一、客户端向服务器的发送消息
代码如下:- public Form1()
- {
- InitializeComponent();
- TextBox.CheckForIllegalCrossThreadCalls = false;//关闭跨线程修改控件检查
- }
- Socket sokClient = null;//负责与该服务端套接字通信的套接字
- Thread threadClient = null;//负责 监听 服务器端发送来的消息的 线程
- bool isRec = true;//是否循环接受服务端的数据
- private void button1_Click(object sender, EventArgs e)
- {
- //实例化 套接字 (ip4寻址协议,流式传输,TCP协议)
- sokClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- //创建IP对象
- IPAddress address = IPAddress.Parse(txtIp.Text.Trim());
- //创建网络节点对象 包含 ip和port
- IPEndPoint endPoint = new IPEndPoint(address, int.Parse(txtPort.Text.ToString().Trim()));
- //创建 服务端监听套接字
- sokClient.Connect(endPoint);
- //创建负责接受 服务端发送来数据的 线程
- threadClient = new Thread(ReceiveMsg);
- threadClient.IsBackground = true;
- threadClient.Start();
- }
- void ReceiveMsg()
- {
- while (isRec)
- {
- byte[] msgArr = new byte[1024 * 1024 * 2];//接受到的消息的缓冲区
- sokClient.Receive(msgArr);
- string strMsg = System.Text.Encoding.UTF8.GetString(msgArr);
- ShowMsg("服务端消息:" + strMsg.ToString().Trim());
- }
- }
- private void btnSendNews_Click(object sender, EventArgs e)
- {
- byte[] arrMsg = System.Text.Encoding.UTF8.GetBytes(txtInput.Text.Trim());//把字符串 转换成 字节
- sokClient.Send(arrMsg);//发送信息
- ShowMsg("我说:" + txtInput.Text.Trim());
- }
- #region 向文本框显示消息 -void ShowMsg(string msg)
- //向文本框显示消息
- void ShowMsg(string msg)
- {
- txtShow.AppendText(msg + "\r\n");
- }
- #endregion
复制代码 二、服务端接受客户端发送的消息
代码如下:- public Form1()
- {
- InitializeComponent();
- TextBox.CheckForIllegalCrossThreadCalls = false;//关闭跨线程修改控件检查
- }
- Socket sokWatch = null;//负责监听 客户端 连接请求的 套接字
- Thread threadWatch = null;//负责调用套接字,执行 监听请求的线程
- //开始监听按钮
- private void button1_Click(object sender, EventArgs e)
- {
- //实例化 套接字 (ip4寻址协议,流式传输,TCP协议)
- sokWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- //创建IP对象
- IPAddress address = IPAddress.Parse(txtIp.Text.Trim());
- //创建网络节点对象 包含 ip和port
- IPEndPoint endPoint = new IPEndPoint(address, int.Parse(txtPort.Text.ToString().Trim()));
- //将 监听套接字 绑定到 对应的IP和端口
- try
- {
- sokWatch.Bind(endPoint);
- }
- catch (Exception ex)
- {
- ShowMsg("异常:" + ex);
- return;
- }
- //设置 监听队列 长度为10(同时能处理10个连接请求)
- sokWatch.Listen(10);
- threadWatch = new Thread(StartWatch);
- threadWatch.IsBackground = true;
- threadWatch.Start();
- ShowMsg("启动服务成功!");
- }
- Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>();
- bool isWatch = true;
- //被线程调用 监听连接端口
- void StartWatch()
- {
- while (isWatch)
- {
- //监听 客户端 连接请求 ,但是,它会阻断当前线程
- Socket sokMsg = sokWatch.Accept();//监听到请求,立即创建负责与该客户端套接字通信的套接字
- //将 通信套接字 加入 集合,并以通信套接字的远程IpPort作为键
- dicSocket.Add(sokMsg.RemoteEndPoint.ToString(), sokMsg);
- cboClient.Items.Add(sokMsg.RemoteEndPoint.ToString());
- ShowMsg("接受连接成功!");
- //启动一个新线程 用来监听客户端发送来的数据
- Thread threadConnection = new Thread(ReciveMsg);
- threadConnection.IsBackground = true;
- threadConnection.Start(sokMsg);
- }
- }
- //发送信息 到指定的客户端
- private void btnSendNews_Click(object sender, EventArgs e)
- {
- byte[] arrMsg = System.Text.Encoding.UTF8.GetBytes(txtInput.Text.Trim());//把字符串 转换成 字节
- //从下拉框中 获得 要向哪个客户端发送消息
- string socketConnection = cboClient.Text.Trim();
- if (!string.IsNullOrEmpty(socketConnection))
- {
- //查字典集合中根据键获得 负责与该客户端负责通信的套接字 并调用send方法发送数据过去
- dicSocket[socketConnection].Send(arrMsg);
- //sokMsg.Send(arrMsg);//发送信息
- ShowMsg("我说:" + txtInput.Text.Trim());
- }
- else
- {
- ShowMsg("消息:请选择发送消息的用户!");
- }
- }
- bool isRec = true;//与客户端通信的 套接字 是否 监听消息
- #region 接受客户端发送来的消息 -void ReciveMsg(Socket sokConnection)
- /// <summary>
- /// 接受客户端发送来的消息
- /// </summary>
- /// <param name="sokConnection">与客户端通信的套接字对象</param>
- void ReciveMsg(object sok)
- {
- Socket sokConnection = sok as Socket;
- if (sokConnection != null)
- {
- try
- {
- while (isRec)
- {
- byte[] msgArr = new byte[1024 * 1024 * 2];//接受到的消息的缓冲区
- int length = sokConnection.Receive(msgArr);
- string strMsg = System.Text.Encoding.UTF8.GetString(msgArr, 0, length);
- ShowMsg(sokConnection .RemoteEndPoint+ "的消息:" + strMsg + "\r\n");
- }
- }
- catch (SocketException ex)
- {
- ShowMsg("异常:" + ex);
- }
- catch (Exception ex)
- {
- ShowMsg("异常:" + ex);
- }
- }
- }
- #endregion
- #region 向文本框显示消息 -void ShowMsg(string msg)
- //向文本框显示消息
- void ShowMsg(string msg)
- {
- txtShow.AppendText(msg + "\r\n");
- }
- #endregion
复制代码 |