C#中Socket用法,多个聊天和单一聊天。
自己琢磨Socket刚刚几天,所以整理出来和大家共享一下。废话少说直接进入正题。
在C#中提供了两种网络服务,一种是Socket类,另一种是TcpListener(服务器),TcpClient(客户端);
至于这两种有什么区别那;MSDN上是这样解释的:
TcpClient 类,TcpListener 类提供了一些简单的方法,用于在同步阻止模式下通过网络来连接、发送和接收流数据。
Socket 类为网络通信提供了一套丰富的方法和属性。 Socket 类允许您使用 ProtocolType 枚举中所列出的任何一种协议执行异步和同步数据传输。
个人理解就是一个是用于简单的业务,一种用于复杂的业务。所以感觉是一样的。本文事例主要用Socket类来实现。一般来说复杂的会了,简单的应该也差不多了。
先从第一个情景来说:第一个就是建立多人聊天的模式,就是多个客户端连接一个服务器,然后可以和多个客户端通信。就像QQ里的群聊。
首先我们来见一个服务器:
就包含一个文本框就行了,里边具体代码如下:
- public partial class server : Form
- {
- private IPEndPoint ServerInfo;//存放服务器的IP和端口信息
- private Socket ServerSocket;//服务端运行的SOCKET
- private Thread ServerThread;//服务端运行的线程
- private Socket[] ClientSocket;//为客户端建立的SOCKET连接
- private int ClientNumb;//存放客户端数量
- private byte[] MsgBuffer;//存放消息数据
- private object obj;
- public server()
- {
- InitializeComponent();
- ListenClient();
- }
- /// <summary>
- /// 开始服务,监听客户端
- /// </summary>
- private void ListenClient()
- {
- try
- {
- ServerSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- IPAddress ip = IPAddress.Parse("127.0.0.1");
- ServerInfo = new IPEndPoint(ip, Int32.Parse(""));
- ServerSocket.Bind(ServerInfo);
- ServerSocket.Listen();
- ClientSocket = new Socket[];
- MsgBuffer = new byte[];
- ClientNumb = ;
- ServerThread = new Thread(new ThreadStart(RecieveAccept));
- ServerThread.Start();
- }
- catch (System.Exception ex)
- {
- }
- }
- /// <summary>
- /// 添加阻塞,监听客户端
- /// </summary>
- private void RecieveAccept()
- {
- while (true)
- {
- //等待接受客户端连接,如果有就执行下边代码,没有就阻塞
- ClientSocket[ClientNumb] = ServerSocket.Accept();
- //接受客户端信息,没有阻塞,则会执行下边输出的代码;如果是Receive则不会执行下边输出代码
- ClientSocket[ClientNumb].BeginReceive(MsgBuffer, , MsgBuffer.Length, SocketFlags.None,
- new AsyncCallback(ReceiveCallback), ClientSocket[ClientNumb]);
- this.Invoke((MethodInvoker)delegate
- {
- lock (this.textBox1)
- this.textBox1.Text += "客户端:" + ClientNumb.ToString() + "连接成功!" + "\r\n";
- });
- ClientNumb++;
- }
- }
- /// <summary>
- /// 回发数据到客户端
- /// </summary>
- /// <param name="ar"></param>
- private void ReceiveCallback(IAsyncResult ar)
- {
- try
- {
- Socket rSocket = (Socket)ar.AsyncState;
- int rEnd = rSocket.EndReceive(ar);
- for (int i = ; i < ClientNumb; i++)
- {
- if (ClientSocket[i].Connected)
- {
- //发送数据到客户端
- ClientSocket[i].Send(MsgBuffer, , rEnd, SocketFlags.None);
- }
- //同时接受客户端回发的数据,用于回发
- rSocket.BeginReceive(MsgBuffer, , MsgBuffer.Length, , new AsyncCallback(ReceiveCallback), rSocket);
- }
- }
- catch (System.Exception ex)
- {
- }
- }
- }
然后我们添加客户端代码,客户端要一个按钮和两个文本框
具体代码如下:
- 1 public partial class Client : Form
- 2 {
- 3 private IPEndPoint ServerInfo;
- 4 private Socket ClientSocket;
- 5 private object obj;
- 6
- 7 //信息接收缓存
- 8 private Byte[] MsgBuffer;
- 9 //信息发送存储
- 10 private Byte[] MsgSend;
- 11
- 12 public Client()
- 13 {
- 14 InitializeComponent();
- 15 ConnectServer();
- 16 this.button1.Click += new EventHandler(button1_Click);
- 17 }
- 18
- 19 /// <summary>
- 20 /// 打开客户端,即连接服务器
- 21 /// </summary>
- 22 private void ConnectServer()
- 23 {
- 24 try
- 25 {
- 26 ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- 27 MsgBuffer = new byte[65535];
- 28 MsgSend = new byte[65535];
- 29 IPAddress ip = IPAddress.Parse("127.0.0.1");
- 30 ServerInfo = new IPEndPoint(ip, Int32.Parse("3000"));
- 31 ClientSocket.Connect(ServerInfo);
- 32 //发送信息至服务器
- 33 ClientSocket.Send(Encoding.Unicode.GetBytes("用户: 进入系统!" + "\r\n"));
- 34 ClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, SocketFlags.None,
- 35 new AsyncCallback(ReceiveCallback), null);
- 36 this.textBox1.Text += "登录服务器成功" + "\r\n";
- 37 }
- 38 catch (System.Exception ex)
- 39 {
- 40
- 41 }
- 42 }
- 43
- 44 /// <summary>
- 45 /// 回调时调用
- 46 /// </summary>
- 47 /// <param name="ar"></param>
- 48 private void ReceiveCallback(IAsyncResult ar)
- 49 {
- 50 int rEnd = ClientSocket.EndReceive(ar);
- 51 this.Invoke((MethodInvoker)delegate
- 52 {
- 53 lock (this.textBox1)
- 54 {
- 55 this.textBox1.Text += Encoding.Unicode.GetString(MsgBuffer, 0, rEnd) + "\r\n";
- 56 }
- 57 });
- 58 ClientSocket.BeginReceive(MsgBuffer, 0, MsgBuffer.Length, 0, new AsyncCallback(ReceiveCallback), null);
- 59 }
- 60
- 61 /// <summary>
- 62 /// 发送信息
- 63 /// </summary>
- 64 /// <param name="sender"></param>
- 65 /// <param name="e"></param>
- 66 private void button1_Click(object sender, EventArgs e)
- 67 {
- 68 MsgSend = Encoding.Unicode.GetBytes("说:\n" + this.textBox2.Text + "\n\r");
- 69 if (ClientSocket.Connected)
- 70 {
- 71 ClientSocket.Send(MsgSend);
- 72 }
- 73 }
- 74
- 75 }
- 76 }
这样先运行服务器,在多运行几个客户端就可以了。
下边讲一下第二种案例:这种是多个客户端和服务器连接,每个客户端都可以和服务器通信,但是客户端之间没有通信,而且每个客户端和服务器通信时,不会影响其他客户端。
具体样式如图:
接着我们来看看具体的代码:
先来看看服务器的,样式和第一种一样,
具体代码:
- public partial class Server : Form
- {
- private Socket socket = null;
- private Thread thread = null;
- public Server()
- {
- InitializeComponent();
- StartListening();
- }
- ///
- /// 开始监听客户端
- ///
- private void StartListening()
- {
- try
- {
- socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- IPAddress ipaddress = IPAddress.Parse("127.0.0.1");
- IPEndPoint endPoint = new IPEndPoint(ipaddress, int.Parse(""));
- socket.Bind(endPoint);
- socket.Listen();
- thread = new Thread(new ThreadStart(WatchConnection));
- thread.IsBackground = true;
- thread.Start();
- this.listBox1.Text = "开始监听客户端传来的消息" + "\r\n";
- }
- catch (System.Exception ex)
- {
- this.listBox1.Text += "SocketException" + ex;
- }
- }
- Socket[] socConnection = new Socket[];
- private static int clientNum = ;
- /// <summary>
- /// 监听客户端发来的请求
- /// </summary>
- private void WatchConnection()
- {
- while (true)
- {
- socConnection[clientNum] = socket.Accept();
- this.Invoke((MethodInvoker)delegate
- {
- this.listBox1.Text += "客户端连接成功" + "\r\n";
- });
- Thread thread = new Thread(new ParameterizedThreadStart(ServerRecMsg));
- thread.IsBackground = true;
- thread.Start(socConnection[clientNum]);
- clientNum++;
- }
- }
- /// <summary>
- /// 接受客户端消息并发送消息
- /// </summary>
- /// <param name="socketClientPara"></param>
- private void ServerRecMsg(object socketClientPara)
- {
- Socket socketServer = socketClientPara as Socket;
- try
- {
- while (true)
- {
- byte[] arrServerRecMsg = new byte[ * ];
- int length = socketServer.Receive(arrServerRecMsg);
- string strSRecMsg = Encoding.UTF8.GetString(arrServerRecMsg, , length);
- this.Invoke((MethodInvoker)delegate
- {
- this.listBox1.Text += "接收到:" + strSRecMsg + "\r\n";
- });
- byte[] arrSendMsg = Encoding.UTF8.GetBytes("收到服务器发来的消息");
- //发送消息到客户端
- socketServer.Send(arrSendMsg);
- }
- }
- catch (System.Exception ex)
- {
- }
- }
- }
再来看看客户端代码:
样式和第一种也一样:
- public partial class Client : Form
- {
- private Socket socketClient = null;
- private Thread threadClient = null;
- public Client()
- {
- InitializeComponent();
- ConnectionServer();
- this.button1.Click += new EventHandler(button1_Click);
- }
- /// <summary>
- /// 连接服务器
- /// </summary>
- private void ConnectionServer()
- {
- socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
- IPAddress ipaddress = IPAddress.Parse("127.0.0.1");
- IPEndPoint endPoint = new IPEndPoint(ipaddress, int.Parse(""));
- try
- {
- socketClient.Connect(endPoint);
- threadClient = new Thread(RecMsg);
- threadClient.IsBackground = true;
- threadClient.Start();
- }
- catch (System.Exception ex)
- {
- }
- }
- /// <summary>
- /// 接收服务器消息
- /// </summary>
- private void RecMsg()
- {
- while (true)
- {
- //内存缓冲区1M,用于临时存储接收到服务器端的消息
- byte[] arrRecMsg = new byte[ * ];
- //将接收到的数据放入内存缓冲区,获取其长度
- int length = socketClient.Receive(arrRecMsg);
- //将套接字获取到的字节数组转换为我们可以理解的字符串
- string strRecMsg = Encoding.UTF8.GetString(arrRecMsg, , length);
- this.Invoke((MethodInvoker)delegate
- {
- lock (this.listBox1)
- {
- this.listBox1.Text += "服务器:" + strRecMsg + "\r\n";
- }
- });
- }
- }
- /// <summary>
- /// 向服务器发送消息
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void button1_Click(object sender, EventArgs e)
- {
- ClientSendMsg(this.textBox1.Text.Trim());
- }
- /// <summary>
- /// 发送信息到服务器
- /// </summary>
- /// <param name="sendMsg"></param>
- private void ClientSendMsg(string sendMsg)
- {
- //将输入的字符串转化为机器可以识别的字节数组
- byte[] arrClientSendMsg = Encoding.UTF8.GetBytes(sendMsg);
- //发送数据
- socketClient.Send(arrClientSendMsg);
- this.listBox1.Text += "客户端:" + sendMsg + "\r\n";
- }
- }
到此两种方式就说完了,不知道说的对不对,请各位吐槽!!!,转载注明出处。
C#中Socket用法,多个聊天和单一聊天。的更多相关文章
- 第一篇 网站基础知识 第4章 Java中Socket的用法
第4章 Java中Socket的用法 4.1 普通Socket的用法 Java中的网络通信是通过Socket实现的,Socket分为ServetSocket和Socket两大类,ServetSocke ...
- Java中的Socket用法
转发链接:https://www.cnblogs.com/zhanglei93/p/6217384.html (1)Java中的Socket用法 Java中的Socket分为普通的Socket和Nio ...
- AgileEAS.NET SOA 中间件平台.Net Socket通信框架-完整应用例子-在线聊天室系统-下载配置
一.AgileEAS.NET SOA中间件Socket/Tcp框架介绍 在文章AgileEAS.NET SOA 中间件平台Socket/Tcp通信框架介绍一文之中我们对AgileEAS.NET SOA ...
- Node.js下基于Express + Socket.io 搭建一个基本的在线聊天室
一.聊天室简单介绍 采用nodeJS设计,基于express框架,使用WebSocket编程之 socket.io机制.聊天室增加了 注册登录模块 ,并将用户个人信息和聊天记录存入数据库. 数据库采用 ...
- java Socket用法详解(转)
在客户/服务器通信模式中, 客户端需要主动创建与服务器连接的 Socket(套接字), 服务器端收到了客户端的连接请求, 也会创建与客户连接的 Socket. Socket可看做是通信连接两端的收发器 ...
- JAVA之旅(三十二)——JAVA网络请求,IP地址,TCP/UDP通讯协议概述,Socket,UDP传输,多线程UDP聊天应用
JAVA之旅(三十二)--JAVA网络请求,IP地址,TCP/UDP通讯协议概述,Socket,UDP传输,多线程UDP聊天应用 GUI写到一半电脑系统挂了,也就算了,最多GUI还有一个提示框和实例, ...
- 操作系统底层原理与Python中socket解读
目录 操作系统底层原理 网络通信原理 网络基础架构 局域网与交换机/网络常见术语 OSI七层协议 TCP/IP五层模型讲解 Python中Socket模块解读 TCP协议和UDP协议 操作系统底层原理 ...
- python中Socket的使用
说明 前一段时间学习python网络编程,完成简单的通过python实现网络通信的功能.现在,将python中Socket 通信的基本实现过程做一个记录备份. Socket通信 python 中的so ...
- [转载]C#中MessageBox.Show用法以及VB.NET中MsgBox用法
一.C#中MessageBox.Show用法 MessageBox.Show (String) 显示具有指定文本的消息框. 由 .NET Compact Framework 支持. MessageBo ...
随机推荐
- C语言 处理文件
刚学习C语言不久,运用C语言处理各种文件.这里列出,处理文件所需的大部分函数,已经整理的笔记,使用的注意事项.
- Linux如何查找文件安装路径?
Linux中查看某 个软件的安装路径(地址)有时显得非常重要.比如某个文件的快速启动项被删除,或者你要建立快速启动项,或者想删除. 添加安装文件等等,很多地方都要用到查案文件安装路径的命令. 这里给大 ...
- AndroidHttp通信 HTTP Client与HttpURLConnection的区别
Apache HTTP Client DefaultHttpClient 以及其相关类AndroidHttpClient 适用于 web browsers, 他们是可扩展的,并且拥有大量的稳定APIs ...
- Request的getParameter和getAttribute方法的区别
下面整理一下getParameter和getAttribute的区别和各自的使用范围. (1)HttpServletRequest类有setAttribute()方法,而没有setParam ...
- 《Pro Android Graphics》读书笔记之第四节
Android Procedural Animation: : XML, Concepts and Optimization Procedural Animation Concepts: Tweens ...
- Java的finally理解
1.为什么要用finally 先看一个没有finally的异常处理try-catch语句: 如果count为要使用到的资源,而且用完要求释放此资源.那么我们能够把释放资源的语句放到try-catch后 ...
- [D3] 14. Line and Area Charts with D3
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...
- List<T>实体去重分组:
实体去重分组: //实体类 public class Province { public string id { get; set; } public string name { get; set; ...
- JDBC Transaction Management Example---reference
In this post, we want to talk about JDBC Transactions and how we can manage the operations in a data ...
- android开发之使用拼音搜索汉字
国庆回了趟家,昨天真不想走,离家近的感觉太好.唉,不扯这些,说说今天的正事吧. 上篇博客中介绍了自定义AutoCompleteTextView ,但是用到了一个很蹩脚的技术,就是我们事先把每个汉字的拼 ...