1.创建监听线程
/// <summary> ///1. 线程监听操作 /// </summary> private void ThreadServerListen() { //接收数据线程 Thread ReceiveThread = new Thread(new ThreadStart(StartServerListenAndReceiveData)); * //后台运行 ReceiveThread.IsBackground = true; //开启线程 ReceiveThread.Start(); }
2.开始监听
/// <summary> ///2 开始监听 /// </summary> private void StartServerListenAndReceiveData() { try { //如果没有绑定则执行绑定当地终结点操作 if (!ServerSocket.IsBound) { //设置终结点 SetEndPoint();
//绑定本地结点 ServerSocket.Bind(ServerEndPoint); //开启监听 ServerSocket.Listen(20); listBox1.Text = string.Format("成功开启监听(Ip:{0} 端口:{1}) 时间:[{2}] \n", ServerEndPoint.Address, ServerEndPoint.Port, DateTime.Now.ToString()); ClientSocket = ServerSocket.Accept(); //接受连接 } //接收数据开始 ServerReceiveData(); * } catch { MessageBox.Show(string.Format("开启监听{0}:{1}失败!请检查服务端IP地址是否配置正确。", ServerEndPoint.Address, ServerEndPoint.Port), "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary>
/// 设置服务器端终结点
/// </summary>
private void SetEndPoint()
{
IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName());
IPAddress address = hostEntry.AddressList[0];//
ServerEndPoint = new IPEndPoint(address, SERVER_END_POINT_PORT);
}
3. 开始接收数据
/// <summary> ///3 接收数据 /// </summary> private void ServerReceiveData() { try { while (true) { Thread.Sleep(1); byte[] bytes = new byte[1024]; //接收数据 int butter = ClientSocket.Receive(bytes); string strData = ""; if (butter > 0) { //接收的数据 strData = Encoding.Default.GetString(bytes); listBox1.Text += "接收到的数据为:" + strData + "\r\n"; } //创建发送线程 ThreadClientrSendData(strData); * ////客户端SOCKET ClientSocket = ServerSocket.Accept(); //继续接受链接 } } catch (Exception err) { MessageBox.Show(err.ToString()); } } #endregion
4.创建发送数据线程
/// <summary> ///4. 线程发送数据 /// </summary> private void ThreadClientrSendData(string jasondata) { Thread thread = new Thread(new ParameterizedThreadStart(ClientSendData)); thread.IsBackground = true; thread.Priority = ThreadPriority.Highest; thread.Start(jasondata); }
5.开始发送数据
//str 接受的数据 private void ClientSendData(object str) { //4.转换byte byte[] sendByte = Encoding.Default.GetBytes(JsonData); //重新调整客户端端口号 ClientEndPoint = (IPEndPoint)ClientSocket.RemoteEndPoint; ClientEndPoint = new IPEndPoint(ClientEndPoint.Address, ClientEndPoint.Port); //向客户端发送数据 ClientSocket.Send(sendByte); listBox1.Text += "\r\n 发送的数据为:" + BallJason + "\r\n"; }