zoukankan      html  css  js  c++  java
  • Socket实现简单的聊天通信

    最近学习了Socket后,感觉Socket挺好玩的,在博客中看到socket在实时聊天功能的很强大,于是乎就做了一个简单的聊天功能,今天贴出来,能够与大家一起共享,有不对之处,能够给予指出,谢谢!

    服务器中的代码:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Net.Sockets;
    using System.Threading;
    using System.Net;
    
    namespace Chat_SocketServer
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                TextBox.CheckForIllegalCrossThreadCalls = false;
            }
    
            //服务端 监听套接字
            Socket socketWatch = null;
            //服务端 监听线程
            Thread threadWatch = null;
            //字典集合:保存通信套接字
            Dictionary<string,Socket> dictCon = new Dictionary<string,Socket>();
    
            private void Watch_Click(object sender, EventArgs e)
            {
                try { 
                    //1.创建监听套接字 使用 ip4协议,流式传输,TCP连接 
                    socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
                    //2.绑定端口 
                    //2.1获取网络节点对象 
                    IPAddress address = IPAddress.Parse(ip_txt.Text); 
                    IPEndPoint endPoint = new IPEndPoint(address, int.Parse(port_txt.Text)); 
                    
                    //2.2绑定端口(其实内部 就向系统的 端口表中 注册 了一个端口,并指定了当前程序句柄) 
                    socketWatch.Bind(endPoint); 
                    //2.3设置监听队列 
                    socketWatch.Listen(10); 
                    //2.4开始监听,调用监听线程 执行 监听套接字的 监听方法 
                    threadWatch = new Thread(WatchConnecting); 
                    threadWatch.IsBackground = true; 
                    threadWatch.Start(); 
                    ShowMsg("服务器成功启动啦!"); 
                } catch (Exception ex) { 
                    MessageBox.Show(ex.Message); 
                    throw; 
                }   
            }
    
            private void Send_Click(object sender, EventArgs e)
            {
               
                    string strClient = this.lbOnline.Text;
                    if (string.IsNullOrEmpty(strClient))
                    {
                        MessageBox.Show("请选择你要发送消息的客户端!");
                        return;
                    }
                    if (dictCon.ContainsKey(strClient))
                    {
                        string strMsg = this.send_txt.Text.Trim();
                        ShowMsg("
    向客户端【" + strClient + "】说:" + strMsg);
                        //使用 指定的 通信套接字 将 字符串 发送到 指定的客户端 
                        byte[] arrMsg = System.Text.Encoding.UTF8.GetBytes(strMsg);
                        dictCon[strClient].Send(arrMsg);
                    }
                    this.send_txt.Text = "";
            }
    
            void WatchConnecting() { 
                //2.4开始监听:此方法会阻断当前线程,直到有 其它程序 连接过来,才执行完毕 
                Socket sokMsg = socketWatch.Accept(); 
                //将当前连接成功的 【与客户端通信的套接字】 的 标识 保存起来,并显示到 列表中 
                //将 远程客户端的 ip和端口 字符串 存入 列表 
                this.lbOnline.Items.Add(sokMsg.RemoteEndPoint.ToString()); 
                //将 服务端的通信套接字 存入 字典集合 
                dictCon.Add(sokMsg.RemoteEndPoint.ToString(), sokMsg);
                ShowMsg("
    客户端【" + sokMsg.RemoteEndPoint.ToString() + "】上线了!"); 
                //2.5创建 通信线程 
                Thread thrMsg = new Thread(ReceiveMsg); 
                thrMsg.IsBackground = true; 
                thrMsg.Start(sokMsg); 
            } 
            void ReceiveMsg(object obj) { 
                try { 
                    Socket sokMsg = obj as Socket; 
                    //3.通信套接字 监听 客户端的 消息 
                    //3.1创建 消息缓存区 
                    byte[] arrMsg = new byte[1024 * 1024 * 1];
                    while (true) { 
                        //3.2接收客户端的消息 并存入 缓存区,注意:Receive方法也会阻断当前的线程 
                        sokMsg.Receive(arrMsg); 
                        //3.3将接收到的消息 转成 字符串 
                        string strMsg = System.Text.Encoding.UTF8.GetString(arrMsg); 
                        //3.4将消息 显示到 文本框 
                        ShowMsg("
    " + strMsg); 
                    } 
                } catch (Exception ex) { 
                    MessageBox.Show(ex.Message); throw;
                } 
            }
            void ShowMsg(string strmsg) { 
                this.show_txt.AppendText(strmsg + "
    "); 
            } 
        }
    }

    客户端的代码:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Net.Sockets;
    using System.Threading;
    using System.Net;
    
    namespace Chat_SocketClient
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                TextBox.CheckForIllegalCrossThreadCalls = false;
            }
            //客户端 通信套接字
            Socket socketMsg = null;
            //客户端 通信线程 
            Thread threadMsg = null;
            //标记任务
            bool isRec = true;
    
            private void Conn_Click(object sender, EventArgs e)
            {
                try { 
                    //1.创建监听套接字 使用 ip4协议,流式传输,TCP连接 
                    socketMsg = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
                    //2.获取要连接的服务端 节点 
                    //2.1获取网络节点对象 
                    IPAddress address = IPAddress.Parse(ip_textbox.Text); 
                    IPEndPoint endPoint = new IPEndPoint(address, 
                        int.Parse(port_textbox.Text)); 
                    //3.向服务端 发送链接请求 
                    socketMsg.Connect(endPoint); 
                    ShowMsg("连接服务器成功~~!"); 
                    //4.开启通信线程 
                    threadMsg = new Thread(RecevieMsg); 
                    threadMsg.IsBackground = true; 
                    threadMsg.Start(); 
                } catch (Exception ex) { 
                    MessageBox.Show(ex.Message); 
                    throw; 
                } 
            }
    
            private void Send_Click(object sender, EventArgs e)
            {
                string strMsg = this.info_textbox.Text.Trim();
                byte[] arrMsg = System.Text.Encoding.UTF8.GetBytes(strMsg);
                ShowMsg("
    我说:" + strMsg); 
                socketMsg.Send(arrMsg); 
                this.info_textbox.Text = "";
            }
    
            void RecevieMsg() { 
                try { 
                    //3.1创建 消息缓存区 
                    byte[] arrMsg = new byte[1024 * 1024 * 1];
                    while (isRec) { 
                        socketMsg.Receive(arrMsg); 
                        string strMsg = System.Text.Encoding.UTF8.GetString(arrMsg); 
                        ShowMsg("
    服务器说:" + strMsg); 
                     } 
                } catch (Exception ex) {
                       MessageBox.Show(ex.Message); 
                       throw; 
                  } 
            } 
            void ShowMsg(string strmsg) { 
                this.richTextBox1.AppendText(strmsg + "
    ");
            } 
           
        }
    }

    相关资料推荐:http://www.newxing.com/Tech/DotNet/CSharp/Socket_133.html写的聊天通信也很不错哟!

  • 相关阅读:
    filter函数和map函数
    生成器面试题
    装饰器激活生成器
    移动平均値
    send()方法的初识
    监听文件的输入
    迭代器抛出异常处理方法
    装饰器-wraps
    多个装饰器装饰一个函数
    WebView 安卓原生java与h5,js交互
  • 原文地址:https://www.cnblogs.com/ysq0908/p/5816268.html
Copyright © 2011-2022 走看看