服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - C#用websocket实现简易聊天功能(客户端)

C#用websocket实现简易聊天功能(客户端)

2022-12-26 14:01antRain C#

这篇文章主要为大家详细介绍了C#用websocket实现简易聊天功能,客户端方向,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了C#用websocket实现简易聊天功能的具体代码,供大家参考,具体内容如下

前言

使用C#语言进行开发,基于.NET FrameWork4
功能包含群聊,和私聊
参考C# 利用websocket实现简易聊天功能——服务端

界面

C#用websocket实现简易聊天功能(客户端)

界面设计代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
namespace chat_client
{
    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.buttonSend = new System.Windows.Forms.Button();
            this.textBoxMsg = new System.Windows.Forms.TextBox();
            this.textBoxLog = new System.Windows.Forms.TextBox();
            this.buttonStart = new System.Windows.Forms.Button();
            this.labelPort = new System.Windows.Forms.Label();
            this.textBoxPort = new System.Windows.Forms.TextBox();
            this.labelIP = new System.Windows.Forms.Label();
            this.textBoxIP = new System.Windows.Forms.TextBox();
            this.labelName = new System.Windows.Forms.Label();
            this.textBoxName = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            // 
            // buttonSend
            // 
            this.buttonSend.Location = new System.Drawing.Point(769, 504);
            this.buttonSend.Name = "buttonSend";
            this.buttonSend.Size = new System.Drawing.Size(99, 43);
            this.buttonSend.TabIndex = 15;
            this.buttonSend.Text = "发送";
            this.buttonSend.UseVisualStyleBackColor = true;
            this.buttonSend.Click += new System.EventHandler(this.buttonSend_Click);
            // 
            // textBoxMsg
            // 
            this.textBoxMsg.Location = new System.Drawing.Point(36, 504);
            this.textBoxMsg.Name = "textBoxMsg";
            this.textBoxMsg.Size = new System.Drawing.Size(653, 25);
            this.textBoxMsg.TabIndex = 14;
            // 
            // textBoxLog
            // 
            this.textBoxLog.Location = new System.Drawing.Point(36, 78);
            this.textBoxLog.Multiline = true;
            this.textBoxLog.Name = "textBoxLog";
            this.textBoxLog.Size = new System.Drawing.Size(832, 406);
            this.textBoxLog.TabIndex = 13;
            // 
            // buttonStart
            // 
            this.buttonStart.Location = new System.Drawing.Point(726, 18);
            this.buttonStart.Name = "buttonStart";
            this.buttonStart.Size = new System.Drawing.Size(142, 45);
            this.buttonStart.TabIndex = 12;
            this.buttonStart.Text = "连接服务器";
            this.buttonStart.UseVisualStyleBackColor = true;
            this.buttonStart.Click += new System.EventHandler(this.buttonStart_Click);
            // 
            // labelPort
            // 
            this.labelPort.AutoSize = true;
            this.labelPort.Location = new System.Drawing.Point(267, 33);
            this.labelPort.Name = "labelPort";
            this.labelPort.Size = new System.Drawing.Size(54, 15);
            this.labelPort.TabIndex = 11;
            this.labelPort.Text = "port:";
            // 
            // textBoxPort
            // 
            this.textBoxPort.Location = new System.Drawing.Point(327, 33);
            this.textBoxPort.Name = "textBoxPort";
            this.textBoxPort.Size = new System.Drawing.Size(100, 25);
            this.textBoxPort.TabIndex = 10;
            this.textBoxPort.Text = "6666";
            // 
            // labelIP
            // 
            this.labelIP.AutoSize = true;
            this.labelIP.Location = new System.Drawing.Point(74, 33);
            this.labelIP.Name = "labelIP";
            this.labelIP.Size = new System.Drawing.Size(31, 15);
            this.labelIP.TabIndex = 9;
            this.labelIP.Text = "IP:";
            // 
            // textBoxIP
            // 
            this.textBoxIP.Location = new System.Drawing.Point(125, 30);
            this.textBoxIP.Name = "textBoxIP";
            this.textBoxIP.Size = new System.Drawing.Size(100, 25);
            this.textBoxIP.TabIndex = 8;
            this.textBoxIP.Text = "127.0.0.1";
            // 
            // labelName
            // 
            this.labelName.AutoSize = true;
            this.labelName.Location = new System.Drawing.Point(473, 33);
            this.labelName.Name = "labelName";
            this.labelName.Size = new System.Drawing.Size(67, 15);
            this.labelName.TabIndex = 17;
            this.labelName.Text = "用户名:";
            // 
            // textBoxName
            // 
            this.textBoxName.Location = new System.Drawing.Point(546, 30);
            this.textBoxName.Name = "textBoxName";
            this.textBoxName.Size = new System.Drawing.Size(100, 25);
            this.textBoxName.TabIndex = 16;
            this.textBoxName.Text = "ant1";
            // 
            // Form1
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(904, 564);
            this.Controls.Add(this.labelName);
            this.Controls.Add(this.textBoxName);
            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.ResumeLayout(false);
            this.PerformLayout();
 
        }
 
        #endregion
 
        private System.Windows.Forms.Button buttonSend;
        private System.Windows.Forms.TextBox textBoxMsg;
        private System.Windows.Forms.TextBox textBoxLog;
        private System.Windows.Forms.Button buttonStart;
        private System.Windows.Forms.Label labelPort;
        private System.Windows.Forms.TextBox textBoxPort;
        private System.Windows.Forms.Label labelIP;
        private System.Windows.Forms.TextBox textBoxIP;
        private System.Windows.Forms.Label labelName;
        private System.Windows.Forms.TextBox textBoxName;
    }
}

源代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
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_client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        public Socket clientSocket;
       
 
        private void buttonStart_Click(object sender, EventArgs e)
        {
            // 客户端连接服务器
            // 1 创建socket对象
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //2、绑定ip和端口
            String ip = textBoxIP.Text;
            int port = Convert.ToInt32(textBoxPort.Text);
            try
            {
                clientSocket.Connect(new IPEndPoint(IPAddress.Parse(ip), port));
            }
            catch
            {
                MessageBox.Show("连接服务器失败");
            }
            //4、发送name
            byte[] data = Encoding.Default.GetBytes(textBoxName.Text);
            clientSocket.Send(data, 0, data.Length, SocketFlags.None);
            //3、接受消息
            Thread thread = new Thread(new ParameterizedThreadStart(recevie));
            thread.IsBackground = true;// 设置为后台线程
            thread.Start(clientSocket);
            buttonStart.Enabled = false;
        }
 
        private void recevie(object socket)
        {
            var proxSocket = socket as Socket;
            byte[] data = new byte[1024 * 1024];
            String msg;
            int len = 0;
            while (true)
            {
                try
                {
                    len = proxSocket.Receive(data, 0, data.Length, SocketFlags.None);
                }
                catch
                {
                    stopConnect();//关闭连接
                    return;
                }
 
                if (len <= 0)
                {
                    //客户端正常退出
                    msg = String.Format("服务器{0}发送异常",
                   proxSocket.RemoteEndPoint.ToString());
                    stopConnect();//关闭连接
                    return;//结束当前接受客户端数据的异步线程
                }
                //显示消息
                msg = Encoding.Default.GetString(data, 0, len);
                showLog(msg);
            }
        }
 
        private void stopConnect()
        {
            try
            {
                if (clientSocket.Connected)
                {
                    clientSocket.Shutdown(SocketShutdown.Both);
                    clientSocket.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)
        {
            if (clientSocket.Connected)
            {
                //先判断是否还有服务器处于连接状态
                byte[] data = Encoding.Default.GetBytes(textBoxMsg.Text);
                clientSocket.Send(data, 0, data.Length, SocketFlags.None);
                textBoxMsg.Text = "";
            }
            else
            {
                MessageBox.Show("与服务器断开连接");
            }
        }
    }
}

运行截图

打开多个运行程序,在项目生成可执行文件后,在项目文件目录下,找到bin\Debug
可以点击几个可执行程序

C#用websocket实现简易聊天功能(客户端)

C#用websocket实现简易聊天功能(客户端)

C#用websocket实现简易聊天功能(客户端)

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

原文链接:https://blog.csdn.net/qq_41146650/article/details/105531817

延伸 · 阅读

精彩推荐
  • C#C# 复制指定节点的所有子孙节点到新建的节点下

    C# 复制指定节点的所有子孙节点到新建的节点下

    这篇文章主要介绍了C# 复制指定节点的所有子孙节点到新建的节点下的相关资料,非常不错具有一定的参考借鉴价值,需要的朋友可以参考下...

    zhyue937322021-12-08
  • C#C# 实现FTP上传资料的示例

    C# 实现FTP上传资料的示例

    这篇文章主要介绍了C# 实现FTP上传资料的示例,帮助大家更好的理解和学习c#,感兴趣的朋友可以了解下...

    農碼一生7952022-10-20
  • C#C#使用checkedListBox1控件链接数据库的方法示例

    C#使用checkedListBox1控件链接数据库的方法示例

    这篇文章主要介绍了C#使用checkedListBox1控件链接数据库的方法,结合具体实例形式分析了数据库的创建及checkedListBox1控件连接数据库的相关操作技巧,需要的朋...

    a7719485247622022-01-12
  • C#C#从foreach语句中枚举元素看数组详解

    C#从foreach语句中枚举元素看数组详解

    这篇文章主要给大家介绍了关于C#从foreach语句中枚举元素看数组的相关资料,文中介绍的非常详细,对大家具有一定的参考学习价值,需要的朋友们下面来...

    Simen.Net5802022-01-05
  • C#Unity多语言转换工具的实现

    Unity多语言转换工具的实现

    这篇文章主要为大家详细介绍了Unity多语言转换工具的实现,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下...

    贝塔小可爱5612022-09-20
  • C#基于c#用Socket做一个局域网聊天工具

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

    目前基于Internet的即时聊天工具已经做的非常完美,本文介绍了基于c#用Socket做一个局域网聊天工具,有需要的朋友可以看一下。...

    Create Chen10222021-12-08
  • C#C# 获取系统字体的示例代码

    C# 获取系统字体的示例代码

    这篇文章主要介绍了C# 获取系统字体的方法,文中讲解非常细致,帮助大家更好的理解和学习,感兴趣的朋友可以了解下...

    唐宋元明清218810272022-09-26
  • C#C# 位图BitArray的使用

    C# 位图BitArray的使用

    如果我们着重处理一个以位为单位的数据时,就可以考虑使用位数组。本文就介绍了C# 位图BitArray的使用,感兴趣的可以了解一下...

    有态度的马甲5952022-11-24