各位大神,现在我做的一个winform控制系统,从测试客户端发送数据到服务器端,为什么只是第一次能够接收到数据后面就没反应了,这个问题苦恼了我很久,请帮我看一下,服务器端界面设计和代码如下所示,测试客户端是一个测试工具。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace 路灯控制系统
{
public partial class Form1 : Form
{
Thread threadWatch=null; //负责监听客户端连接请求
Socket socketWatch=null;
Dictionary<string, Socket> dictSocket = new Dictionary<string, Socket>();
Dictionary<string, Thread> dictThread = new Dictionary<string, Thread>();
public Form1()
{
InitializeComponent();
TextBox.CheckForIllegalCrossThreadCalls = false; //可以跨线程调用
}
//16进制字符串转字节数组
private static byte[] strToToHexByte(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
hexString += " ";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}
/// <summary>
/// 字节数组转16进制字符串
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static string byteToHexStr(byte[] bytes)
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
returnStr += bytes[i].ToString("X2");
}
}
return returnStr;
}
private void btnBeginListen_Click(object sender, EventArgs e)
{
//首先创建负责监听的套接字
socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//创建本地IP对象
IPAddress ip = IPAddress.Parse(txtIP.Text.Trim());
//创建包含服务器本地监听端口的EndPoint
IPEndPoint endPoint = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text.Trim()));
try
{
//绑定要监听的服务器端口
socketWatch.Bind(endPoint);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
return;
}
socketWatch.Listen(100);
threadWatch = new Thread(WatchConnecting);
threadWatch.IsBackground = true;
threadWatch.Start();
ShowMsg("服务器启动成功!");
}
/// <summary>
/// 监控客户端传来的信息
/// </summary>
private void WatchConnecting()
{
//应用循环不间断地监控客户端传来的连接请求
while(true )
{
//开始监听客户端请求,accept会阻断当前线程,要注意
Socket socketConnection = socketWatch.Accept(); //一旦监听到客户端的连接请求,就新生成一个客户端相关的套接字
//向客户端连接列表控件listbbox中添加建立连接的客户端
lbOnline.Items.Add(socketConnection.RemoteEndPoint.ToString());
//将成功连接的套接字添加进列表中去
dictSocket.Add(socketConnection.RemoteEndPoint.ToString(), socketConnection);
ShowMsg("客户端连接成功!");
Thread th = new Thread(ReceiveMsg);
th.IsBackground = true;
th.Start(socketConnection);
dictThread.Add(socketConnection.RemoteEndPoint.ToString(), th);
}
}
/// <summary>
/// 在文本框显示提示信息
/// </summary>
/// <param name="str"></param>
private void ShowMsg(string str)
{
txtMsg.AppendText ( str + "\r\n");
}
/// <summary>
/// 接收连接客户端传过来的数据
/// </summary>
/// <param name="socketConnection">客户端套接字</param>
private void ReceiveMsg(object socketConnection)
{
Socket socketClient= (Socket)socketConnection;
while (true )
{
//定义一个2M的缓存区,将接收的数据存入其中
byte[] arrMsgRec = new byte[2 * 1024 * 1024];
int length = -1;
try
{
length = socketClient.Receive(arrMsgRec); //接收客户端传过来的数据并且返回数据长度
}
catch (SocketException ex)
{
ShowMsg("客户端连接异常:"+ex.ToString ());
dictSocket.Remove(socketClient.RemoteEndPoint.ToString());
dictThread.Remove(socketClient.RemoteEndPoint.ToString());
lbOnline.Items.Remove(socketClient.RemoteEndPoint.ToString());
//MessageBox.Show(ex.ToString());
break;
}
if(length>0)
{
string str = "接收信息如下:" + byteToHexStr(arrMsgRec).Substring(0, length * 2);
ShowMsg(str);
}
socketClient.Close();
}
}
/// <summary>
/// 发送消息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnSend_Click(object sender, EventArgs e)
{
string strMsg = txtMsgSend.Text.Trim();
byte[] arrSendMsg = strToToHexByte(strMsg); // 将要发送的字符串转换成16进制字节数组;
string strKey = "";
strKey = lbOnline.Text.Trim();
if (string.IsNullOrEmpty(strKey)) // 判断是不是选择了发送的对象;
{
MessageBox.Show("请选择你要发送的好友!!!");
}
else
{
dictSocket[strKey].Send(arrSendMsg);// 解决了 sokConnection是局部变量,不能再本函数中引用的问题;
ShowMsg("发送信息:"+strMsg);
txtMsgSend.Clear();
}
}
}
}