if (flag)
{
Thread RecMsgthd = new Thread(RecMsg);
RecMsgthd.IsBackground = true;
RecMsgthd.Start(sokConnection);
}
这一块一直读不到,是什么原因呢?- public Form1()
- {
- InitializeComponent();
- TextBox.CheckForIllegalCrossThreadCalls = false;
- }
- Socket socketWatch;
- Dictionary<string, Socket> dict = new Dictionary<string, Socket>();
- bool flag = false;
- private void btnBegin_Click(object sender, EventArgs e)
- {
- //创建负责监听的套接字,参数(使用IP4寻址协议,使用流式连接,使用TCP协议传输数据 )
- socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- //获得文本框中的IP地址对象
- IPAddress adress = IPAddress.Parse(txtIP.Text.Trim());
- //创建包含ip和端口的网络节点对象
- IPEndPoint endpoint = new IPEndPoint(adress, int.Parse(txtPORT.Text.Trim()));
- //将负责监听的套接字 绑定到唯一IP和端口上
- socketWatch.Bind(endpoint);
- // 设置监听队列的长度
- socketWatch.Listen(10);
- //创建负责监听的线程,并传入监听的方法
- Thread watch = new Thread(ConnectionThd);
- watch.IsBackground = true;
- watch.Start();//开启线程
- ShowMsg("启动成功");
- if (flag)
- {
- Thread RecMsgthd = new Thread(RecMsg);
- RecMsgthd.IsBackground = true;
- RecMsgthd.Start(sokConnection);
- }
- }
- Socket sokConnection;
- /// <summary>
- /// 监听客户端请求的方法
- /// </summary>
- void ConnectionThd()
- {
- while (true)
- {
- //开始监听客户端请求,注意Accpeet,会阻断当前进程
- sokConnection = socketWatch.Accept();//一旦监听到客户端请求,就返回和客户端通信的套接字
- //想列表控件中 添加一个 客户端的IP端口字符串,作为客户端的唯一标识
- lbOnline.Items.Add(sokConnection.RemoteEndPoint.ToString());
- //将 与客户端通信的套接字对象sokConnection 添加到 键值对集合中,并以客户端IP端口作为键
- dict.Add(sokConnection.RemoteEndPoint.ToString(), sokConnection);
- //Thread thdRec = new Thread(RecMsg);
- //thdRec.IsBackground = true;
- //thdRec.Start(sokConnection);
- flag = true;
- ShowMsg("客户端连接成功");
- }
- }
- void ShowMsg(string msg)
- {
- txtMsg.AppendText(msg + "\n");
- }
- void RecMsg(object socketClientPara)
- {
- Socket socketClient = socketClientPara as Socket;
- while (true)
- {
- //第一个接受用的缓存区(2M)
- byte[] arrMsgRec = new byte[1024 * 1024 * 2];
- int length = socketClient.Receive(arrMsgRec);
- string strMsgRec = System.Text.Encoding.UTF8.GetString(arrMsgRec, 0, length);
- ShowMsg(sokConnection.RemoteEndPoint.ToString() + "发送了数据:" + strMsgRec);
- }
- }
- private void btnSend_Click(object sender, EventArgs e)
- {
- string strMsg = txtSend.Text.Trim();
- byte[] arrMsg = System.Text.Encoding.UTF8.GetBytes(strMsg);
- //获取列表中 选中的key
- string ClientKey = lbOnline.Text;
- //通过key,找到字典集合中对应的 与某客户通信的套接字的send方法,发送数据给对方
- dict[ClientKey].Send(arrMsg);
- //sokConnection.Send(arrMsg);
- ShowMsg("发送了数据" + strMsg);
-
- }
复制代码 |