这篇文章主要为大家详细介绍了C#用websocket实现简易聊天功能,客户端方向,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了C#用websocket实现简易聊天功能的具体代码,供大家参考,具体内容如下
前言
使用C#语言进行开发,基于.NET FrameWork4
功能包含群聊,和私聊
参考C# 利用websocket实现简易聊天功能——服务端
界面
界面设计代码
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;
}
}
源代码
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实现简易聊天功能(客户端)
基础教程推荐
猜你喜欢
- unity实现动态排行榜 2023-04-27
- linux – 如何在Debian Jessie中安装dotnet core sdk 2023-09-26
- C# 调用WebService的方法 2023-03-09
- C#类和结构详解 2023-05-30
- ZooKeeper的安装及部署教程 2023-01-22
- winform把Office转成PDF文件 2023-06-14
- C# List实现行转列的通用方案 2022-11-02
- 一个读写csv文件的C#类 2022-11-06
- C#控制台实现飞行棋小游戏 2023-04-22
- C# windows语音识别与朗读实例 2023-04-27