C# 利用websocket实现简易聊天功能——服务端

C# 利用websocket实现简易聊天功能——服务端

前言

  • 使用C#语言进行开发,基于.NET FrameWork4
  • 功能包含群聊,和私聊

界面

在这里插入图片描述

界面设计代码
namespace chat_server
{
    partial class Form1
    {
        /// <summary>
        /// 必需的设计器变量。
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// 清理所有正在使用的资源。
        /// </summary>
        /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows 窗体设计器生成的代码

        /// <summary>
        /// 设计器支持所需的方法 - 不要修改
        /// 使用代码编辑器修改此方法的内容。
        /// </summary>
        private void InitializeComponent()
        {
            this.textBoxIP = new System.Windows.Forms.TextBox();
            this.labelIP = new System.Windows.Forms.Label();
            this.labelPort = new System.Windows.Forms.Label();
            this.textBoxPort = new System.Windows.Forms.TextBox();
            this.buttonStart = new System.Windows.Forms.Button();
            this.textBoxLog = new System.Windows.Forms.TextBox();
            this.textBoxMsg = new System.Windows.Forms.TextBox();
            this.buttonSend = new System.Windows.Forms.Button();
            this.SuspendLayout();
            // 
            // textBoxIP
            // 
            this.textBoxIP.Location = new System.Drawing.Point(145, 25);
            this.textBoxIP.Name = "textBoxIP";
            this.textBoxIP.Size = new System.Drawing.Size(100, 25);
            this.textBoxIP.TabIndex = 0;
            this.textBoxIP.Text = "127.0.0.1";
            // 
            // labelIP
            // 
            this.labelIP.AutoSize = true;
            this.labelIP.Location = new System.Drawing.Point(90, 28);
            this.labelIP.Name = "labelIP";
            this.labelIP.Size = new System.Drawing.Size(31, 15);
            this.labelIP.TabIndex = 1;
            this.labelIP.Text = "IP:";
            // 
            // labelPort
            // 
            this.labelPort.AutoSize = true;
            this.labelPort.Location = new System.Drawing.Point(371, 28);
            this.labelPort.Name = "labelPort";
            this.labelPort.Size = new System.Drawing.Size(54, 15);
            this.labelPort.TabIndex = 3;
            this.labelPort.Text = "port:";
            // 
            // textBoxPort
            // 
            this.textBoxPort.Location = new System.Drawing.Point(452, 25);
            this.textBoxPort.Name = "textBoxPort";
            this.textBoxPort.Size = new System.Drawing.Size(100, 25);
            this.textBoxPort.TabIndex = 2;
            this.textBoxPort.Text = "6666";
            // 
            // buttonStart
            // 
            this.buttonStart.Location = new System.Drawing.Point(718, 13);
            this.buttonStart.Name = "buttonStart";
            this.buttonStart.Size = new System.Drawing.Size(142, 45);
            this.buttonStart.TabIndex = 4;
            this.buttonStart.Text = "开启服务";
            this.buttonStart.UseVisualStyleBackColor = true;
            this.buttonStart.Click += new System.EventHandler(this.buttonStart_Click);
            // 
            // textBoxLog
            // 
            this.textBoxLog.Location = new System.Drawing.Point(28, 73);
            this.textBoxLog.Multiline = true;
            this.textBoxLog.Name = "textBoxLog";
            this.textBoxLog.Size = new System.Drawing.Size(832, 406);
            this.textBoxLog.TabIndex = 5;
            // 
            // textBoxMsg
            // 
            this.textBoxMsg.Location = new System.Drawing.Point(28, 499);
            this.textBoxMsg.Name = "textBoxMsg";
            this.textBoxMsg.Size = new System.Drawing.Size(653, 25);
            this.textBoxMsg.TabIndex = 6;
            // 
            // buttonSend
            // 
            this.buttonSend.Location = new System.Drawing.Point(761, 499);
            this.buttonSend.Name = "buttonSend";
            this.buttonSend.Size = new System.Drawing.Size(99, 43);
            this.buttonSend.TabIndex = 7;
            this.buttonSend.Text = "发送";
            this.buttonSend.UseVisualStyleBackColor = true;
            this.buttonSend.Click += new System.EventHandler(this.buttonSend_Click);
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(947, 567);
            this.Controls.Add(this.buttonSend);
            this.Controls.Add(this.textBoxMsg);
            this.Controls.Add(this.textBoxLog);
            this.Controls.Add(this.buttonStart);
            this.Controls.Add(this.labelPort);
            this.Controls.Add(this.textBoxPort);
            this.Controls.Add(this.labelIP);
            this.Controls.Add(this.textBoxIP);
            this.Name = "Form1";
            this.Text = "服务器";
            this.Load += new System.EventHandler(this.Form1_Load);
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

        private System.Windows.Forms.TextBox textBoxIP;
        private System.Windows.Forms.Label labelIP;
        private System.Windows.Forms.Label labelPort;
        private System.Windows.Forms.TextBox textBoxPort;
        private System.Windows.Forms.Button buttonStart;
        private System.Windows.Forms.TextBox textBoxLog;
        private System.Windows.Forms.TextBox textBoxMsg;
        private System.Windows.Forms.Button buttonSend;
    }
}


源代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace chat_server
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

       
        private void Form1_Load(object sender, EventArgs e)
        {

        }
        // socket连接容器
        Dictionary<Socket, String> userContain = new Dictionary<Socket, string>();
        

        private void buttonStart_Click(object sender, EventArgs e)
        {
            try
            {
                //1、创建socket
                Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                //2、绑定ip和端口
                String ip = textBoxIP.Text;
                int port = Convert.ToInt32(textBoxPort.Text);
                socket.Bind(new IPEndPoint(IPAddress.Parse(ip), port));
                //3、开启监听
                socket.Listen(10);//等待连接队列的最大值
                //4、开始接受客户端的链接
                ThreadPool.QueueUserWorkItem(new WaitCallback(connect), socket);
            }
            catch
            {
                MessageBox.Show("启动服务器失败");
            }

        }
        
        private void connect(object socket)
        {
            var serverSockert = socket as Socket;//强制转换
            showLog("服务器正常启动,开始接受客户端的数据");
            byte[] data = new byte[1024];
            int len;
            String name; //客户端的用户名
            while (true)
            {
                try
                {
                    var proxSocket = serverSockert.Accept();//接受连接
                    len = proxSocket.Receive(data, 0, data.Length, SocketFlags.None);//接受客户端的用户名
                    name = Encoding.Default.GetString(data, 0, len);
                    showLog(String.Format("客户端 {0} 用户名 {1} 连接服务器", proxSocket.RemoteEndPoint.ToString(),name));
                    String msg = String.Format("用户{0}上线了", name);
                    sendMsg(msg);
                    userContain[proxSocket] = name;//把对象放入集合中
                    //不停的接受当前链接的客户端发送的消息
                    ThreadPool.QueueUserWorkItem(new WaitCallback(this.recevie), proxSocket);
                }
                catch
                {
                    MessageBox.Show("接受异常");
                    break;
                }
            }
        }

        private void recevie(object socket)
        {
            var proxSocket = socket as Socket;
            byte[] data = new byte[1024 * 1024];//接受,发送数据缓冲区
            String msg;
            int len = 0; // 数据长度
            String name = userContain[proxSocket]; // 客户端名字
            while (true)
            {
                try
                {
                    len = proxSocket.Receive(data, 0, data.Length, SocketFlags.None);
                }
                catch
                {
                    msg = String.Format("客户端{0}异常退出",
                    proxSocket.RemoteEndPoint.ToString());
                    showLog(msg);
                    msg = String.Format("用户{0}下线了", name);
                    sendMsg(msg);
                    userContain.Remove(proxSocket);
                    stopConnect(proxSocket);
                    return;
                }
          
                if (len <= 0)
                {
                    //客户端正常退出
                    msg = String.Format("客户端{0}正常退出",
                    proxSocket.RemoteEndPoint.ToString());
                    showLog(msg);
                    msg = String.Format("用户{0}下线了", name);
                    sendMsg(msg);
                    userContain.Remove(proxSocket);
                    stopConnect(proxSocket);
                    return;//结束当前接受客户端数据的异步线程
                }
                //接受消息
                msg = Encoding.Default.GetString(data, 0, len);
                //私聊信息格式@name:msg
                //name 为用户名 msg 为消息
                bool flag = true;
                if (msg.StartsWith("@"))
                {
                    int index = msg.IndexOf(":");
                    String targetName = msg.Substring(1, index-1);
                    msg = msg.Substring(index + 1);
                    foreach(var user in userContain)
                    {
                        if(targetName.Equals(user.Value)&&user.Key.Connected)
                        {
                            msg = String.Format("用户{0} 单独对你说:{1}",name,msg);
                            data = Encoding.Default.GetBytes(msg);
                            user.Key.Send(data, 0, data.Length, SocketFlags.None);
                            flag = false;
                            break;
                        }
                    }
                }
                if (flag)
                {
                    msg = String.Format("用户{0}:{1}", name, msg);
                    sendMsg(msg);
                }
            }
        }

        private void stopConnect(Socket socket)
        {
            try
            {
                if (socket.Connected)
                {
                    socket.Shutdown(SocketShutdown.Both);
                    socket.Close(100);
                }
            }
            catch
            {

            }
        }

        private void showLog(String msg)
        {
            if (textBoxLog.InvokeRequired)
            {
                //如果是跨线程访问
                textBoxLog.Invoke(new Action<String>(
                   s => {
                       this.textBoxLog.Text += msg+"\r\n"; 
                   }),msg);
            }
            else
            {
                this.textBoxLog.Text += msg;
            }
        }

        private void buttonSend_Click(object sender, EventArgs e)
        {
            //发送消息
            String msg = String.Format("服务器发布通知信息{0}", textBoxMsg.Text);
            sendMsg(msg);
        }

        private void sendMsg(String msg)
        {
            byte[] data = new byte[1024 * 1024];
            data = Encoding.Default.GetBytes(msg);
            foreach (var user in userContain)
            {
                if (user.Key.Connected)
                {
                     user.Key.Send(data, 0, data.Length, SocketFlags.None);
                }
            }
        }
    }
}
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java WebSocket是一种用于实现双向通信的网络协议,可以帮助我们实现简易聊天室。下面是一个基于Java WebSocket实现简易聊天室的示例代码: 首先,我们需要定义一个WebSocket处理程序: ```java @ServerEndpoint("/chat") public class ChatEndpoint { private static Set<Session> sessions = Collections.synchronizedSet(new HashSet<Session>()); @OnOpen public void onOpen(Session session) { sessions.add(session); } @OnMessage public void onMessage(String message, Session session) throws IOException { for (Session s : sessions) { // 过滤自己 if (!s.equals(session)) { s.getBasicRemote().sendText(message); } } } @OnClose public void onClose(Session session) { sessions.remove(session); } } ``` 在这个处理程序中,我们使用`@ServerEndpoint("/chat")`注解指定了WebSocket的端点,即`/chat`。在`onOpen`方法中,我们将新的会话添加到会话集合中。在`onMessage`方法中,我们将接收到的消息广播给所有其他会话。在`onClose`方法中,我们将关闭的会话从会话集合中移除。 接下来,我们需要在`web.xml`文件中配置WebSocket: ```xml <web-app> <display-name>WebSocket Chat</display-name> <servlet> <servlet-name>chat</servlet-name> <servlet-class>org.glassfish.tyrus.servlet.TyrusServlet</servlet-class> <init-param> <param-name>org.glassfish.tyrus.servlet.websocketClassnames</param-name> <param-value>com.example.ChatEndpoint</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>chat</servlet-name> <url-pattern>/chat/*</url-pattern> </servlet-mapping> </web-app> ``` 在这个配置中,我们使用了`org.glassfish.tyrus.servlet.TyrusServlet`作为WebSocket的Servlet。我们将`com.example.ChatEndpoint`指定为WebSocket处理程序的类名,并将其加载到`servlet`中。 现在,我们就可以在HTML页面中使用WebSocket来连接我们的聊天室了: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>WebSocket Chat</title> </head> <body> <input type="text" id="message"> <button onclick="send()">Send</button> <div id="output"></div> <script> var socket = new WebSocket('ws://localhost:8080/chat'); socket.onmessage = function (event) { var output = document.getElementById('output'); output.innerHTML += event.data + '<br>'; }; function send() { var message = document.getElementById('message').value; socket.send(message); } </script> </body> </html> ``` 在这个HTML页面中,我们创建了一个WebSocket连接到`ws://localhost:8080/chat`。当收到消息时,我们将其添加到页面上的`<div>`元素中。当点击发送按钮时,我们将输入框中的文本发送到WebSocket连接中。 这样,我们就完成了一个简易的Java WebSocket聊天室的实现

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值