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);
                }
            }
        }
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • C#制作简单的多人在线即时交流聊天室

    实现网页版的在线聊天室的方法有很多,在没有来到HTML5之前,常见的有:定时轮询.长连接+长轮询.基于第三方插件(如FLASH的Socket),而如果是HTML5,则比较简单,可以直接使用WebSocket,当然HTML5目前在PC端并没有被所有浏览器支持,所以我的这个聊天室仍是基于长连接+长轮询+原生的JS及AJAX实现的多人在线即时交流聊天室,这个聊天室其实是我上周周末完成的,功能简单,可能有些不足,但可以满足在线即时聊天需求,分享也是给大家提供一个思路,大家可以基于此来实现更好的在线即时聊

  • C#使用WebSocket实现聊天室功能

    WebSocket介绍 WebSocket是HTML5开始提供的一种在单个 TCP 连接上进行全双工通讯的协议. 在WebSocket API中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道.两者之间就直接可以数据互相传送. 浏览器通过 JavaScript 向服务器发出建立 WebSocket 连接的请求,连接建立以后,客户端和服务器端就可以通过 TCP 连接直接交换数据. 当你获取 Web Socket 连接后,你可以通过 send() 方法来向服务器发

  • c#基于WinForm的Socket实现简单的聊天室 IM

    1:什么是Socket 所谓套接字(Socket),就是对网络中不同主机上的应用进程之间进行双向通信的端点的抽象. 一个套接字就是网络上进程通信的一端,提供了应用层进程利用网络协议交换数据的机制. 从所处的地位来讲,套接字上联应用进程,下联网络协议栈,是应用程序通过网络协议进行通信的接口,是应用程序与网络协议根进行交互的接口. 2:客服端和服务端的通信简单流程 3:服务端Code: using System; using System.Collections.Generic; using Sys

  • 基于c#用Socket做一个局域网聊天工具

    程序设计成为简单的服务端和客户端之间的通信, 但通过一些方法可以将这两者进行统一起来, 让服务端也成为客户端, 让客户端也成为服务端, 使它们之间可以互相随时不间断的通信. 考虑到实现最原始的服务端和客户端之间的通信所需要的步骤对于写这样的程序是很有帮助的. 作为服务端, 要声明一个Socket A并绑定(Bind)某一个IP+这个IP指定的通信端口, 比如这个是127.0.0.1:9050, 然后开始监听(Listen), Listen可以监听来自多个IP传过来的连接请求, 具体可以同时连接几

  • 分享一个C#编写简单的聊天程序(详细介绍)

    引言 这是一篇基于Socket进行网络编程的入门文章,我对于网络编程的学习并不够深入,这篇文章是对于自己知识的一个巩固,同时希望能为初学的朋友提供一点参考.文章大体分为四个部分:程序的分析与设计.C#网络编程基础(篇外篇).聊天程序的实现模式.程序实现. 程序的分析与设计 1.明确程序功能 如果大家现在已经参加了工作,你的经理或者老板告诉你,"小王,我需要你开发一个聊天程序".那么接下来该怎么做呢?你是不是在脑子里有个雏形,然后就直接打开VS2005开始设计窗体,编写代码了呢?在开始之

  • C# Socket编程实现简单的局域网聊天器的示例代码

    前言 最近在学习C# Socket相关的知识,学习之余,动手做了一个简单的局域网聊天器.有萌生做这个的想法,主要是由于之前家里两台电脑之间想要传输文件十分麻烦,需要借助QQ,微信或者其他第三方应用,基本都要登录,而且可能传输的文件还有大小限制,压缩问题.所以本聊天器的首要目标就是解决这两个问题,做到使用方便(双击启动即用),传文件无限制. 废话不多说,先上图.S-Chat是服务端,C-Chat是客户端,两者除了客户端首次启动后需要设置一下连接的IP地址外,无其他区别.操作与界面都完全相同,对于用

  • C#使用Socket实现局域网聊天

    本文实例为大家分享了C#使用Socket实现局域网聊天的具体代码,供大家参考,具体内容如下 先运行一个java写的局域网聊天,效果图如下 后使用c#图形修改如下: C#代码: servlet服务端 using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using Sys

  • C#使用Socket实现服务器与多个客户端通信(简单的聊天系统)

    扩展: 由于server端是存储了所有server与client的连接对象,因此我们是可以基于此demo的基础上实现聊天系统: * 每当一个与用户发言时,是由server接收到的某个用户的发言信息的,此时服务器端可以通过循环发送该用户发送的信息给每个已经连接连接的用户(排除发送者). Server端代码: class Program { //创建一个和客户端通信的套接字 static Socket SocketWatch = null; //定义一个集合,存储客户端信息 static Dicti

  • C#基于Socket实现多人聊天功能

    本文实例为大家分享了C#基于Socket实现多人聊天功能的具体代码,供大家参考,具体内容如下 服务器 服务器负责接受所有客户端发来的消息,和将接受到的问题群发到其他用户. 代码: using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; namespace ChatRoomService

  • C#使用Socket实现本地多人聊天室

    本文实例为大家分享了C#使用Socket实现本地多人聊天室的具体代码,供大家参考,具体内容如下 [脚本一:Server端] 使用本机地址:127.0.0.1 完整代码 using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading;   namespace ConsoleApp1 {     p

随机推荐