C#TCP通信问题。客户端发送的消息只能收到第一条。客户端必须断开重新连接,服务器才能再次收到信息。为何?
代码如下:
private Socket socketListener = null;
private Thread thread;
private bool flag;
private void button1_Click(object sender, EventArgs e)
{
if (btnStart.Text == "开启服务器")
{
IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
this.socketListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAddress = IPAddress.Parse("192.168.1.109");
int port = Int32.Parse(this.txtPoint.Text);
//hostEntry.AddressList[2].Address
IPEndPoint endPoint = new IPEndPoint(ipAddress, port);
this.socketListener.Bind(endPoint);
flag = true;
this.thread = new Thread(new ThreadStart(this.ReceiveMessage));
this.thread.Start();
btnStart.Text = "关闭服务器";
if (!txtClientMessage.InvokeRequired)
{
txtClientMessage.AppendText("服务器已打开\n\r");
}
}
else
{
this.socketListener.Close();
this.thread.Abort();
this.flag = false;
}
}
#region 接收消息
public delegate void SetTextHandle(string msg);
private void SetText(string text)
{
if (txtClientMessage.InvokeRequired)
{
SetTextHandle set = new SetTextHandle(SetText);
txtClientMessage.Invoke(set, new object[] { text });
}
else
{
this.txtClientMessage.AppendText(text);
}
}
private void ReceiveMessage()
{
while (this.flag)
{
this.socketListener.Listen(30);
Socket socket = this.socketListener.Accept();
byte[] bytesReceive = new byte[1024];
int bytesCount = socket.Receive(bytesReceive);
bool t = socketListener.Connected;
if (bytesCount > 0)
{
string message = Encoding.Default.GetString(bytesReceive) + "\n\r";
SetText(message);
}
}
}
#endregion
------解决方案--------------------
没注意,原来是个按钮事件,稍微修改下
C# code
private void button1_Click(object sender, EventArgs e)
{
if (btnStart.Text == "开启服务器")
{
IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
this.socketListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAddress = IPAddress.Parse("192.168.1.109");
int port = Int32.Parse(this.txtPoint.Text);
IPEndPoint endPoint = new IPEndPoint(ipAddress, port);
this.s