Home > other >  The socket bolt problem connect to several clients
The socket bolt problem connect to several clients

Time:10-26

Each client sends a message that will take the initiative to close the socket connection (to save electricity), and then to connect to the server, sends a message again, because the client is offline for reconnection, each time you connect the client's IP address and port number is different,

C # code below, run time appear replace (LouShou client sent messages), and soon appeared "has stopped work, close the program", the code is as follows, please give guidance:

Public partial class Form1: Form
{
The Socket m_socket;//the server socket

Bool m_bListening;
Bool m_AlreadyBound;
IPEndPoint m_ipe;

Public delegate void ReceiveMessageDelegate (Client Client);
ReceiveMessageDelegate ReceiveMessageDelegate;

Thread m_thread;

Private void button2_Click (object sender, EventArgs e)//start listening
{
M_bListening=true;
StartButton. Enabled=false;
StopButton. Enabled=true;

Int portNumber=int. Parse (textBox1. Text);

M_ipe=new IPEndPoint (IPAddress. Any, portNumber);//the specified port and IP initialization IPEndPoint new instances of a class
M_socket=new Socket (AddressFamily. InterNetwork, SocketType Stream, ProtocolType. Tcp);

if (! M_AlreadyBound)
{
M_socket. Bind (m_ipe);//bind the EndPoint to like (for example: 3000 port and IP address)
//m_socket. Listen (0);//to start listening to
M_socket. Listen (50);//maximum number of connections

M_AlreadyBound=true;
}
M_thread=new Thread (new ThreadStart (Listening));
M_thread. Start ();
}

Void Listening ()
{
While (true)
{
The Client Client=new Client ();

if (null !=client. ClientSocket)
{
Client. ClientSocket. Shutdown (SocketShutdown. The Receive);
Client. ClientSocket. Shutdown (SocketShutdown. Both);
Client. ClientSocket. Close ();
}
Client. ClientSocket=m_socket. The Accept ();//for the new connection to create a new socket
ConnectedLabel. Enabled=true;

ReceiveMessageDelegate=new receiveMessageDelegate (ReceiveMessages);
ReceiveMessageDelegate. The BeginInvoke (client, ReceiveMessagesCallback, "");
}
}

Private void ReceiveMessagesCallback IAsyncResult (AR)
{
ReceiveMessageDelegate. EndInvoke (AR);
}

Private void ReceiveMessages (Client Client)
{
Byte [] receiveBuffer=new byte [1024].

for (int i=0; i <1024; I++)
ReceiveBuffer [I]=(byte), '\ 0';

Try
{
While (0==client. The ClientSocket. The Receive (receiveBuffer))
{
}
}
The catch (Exception ex)
{
}

String strReceiveData=https://bbs.csdn.net/topics/System.Text.UTF8Encoding.UTF8.GetString (receiveBuffer). TrimEnd (' \ 0 ');

If (! String. IsNullOrWhiteSpace (strReceiveData))
{
TextBox2. AppendText (strReceiveData + System. The Environment. The NewLine);
}
. .
  • Related