C#之Socket编程
将我自己练习的C#Socket代码奉上,至于Socket是干什么的就不用我在此过多赘述了。
下面两段代码,一个为服务端,一个味客户端。
代码中注释非常详细,所以就不过多说明了。
服务端代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;//引入明明空间
using System.Net.Sockets;
using System.Net;
using System.Threading;//服务端
namespace SocketTest
{class Program{ //制定端口号为 10000private static int myProt = 10000; private static Socket serverSocket; //定义Socket对象static void Main(string[] args){//服务器IP地址IPAddress ip = IPAddress.Parse("127.0.0.1");//实例化Socket对象,指明为 Tcp协议,如果用UDP协议,则要用SocketType.Dagram类型的套接字serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//绑定IP地址和端口号serverSocket.Bind(new IPEndPoint(ip, myProt));//设定最多接受100个连接serverSocket.Listen(100);Console.WriteLine("启动监听{0}成功", serverSocket.LocalEndPoint.ToString());//通过ClientSocket发送数据//启动一个线程,线程调用方法为 ListenClientConentThread myThread = new Thread(ListenClientConent);//启动线程,不带参数myThread.Start();Console.ReadLine();}//监听客户端请求private static void ListenClientConent(){while (true){//定义一个Socket对象接受连接到的Socket实例Socket clientSocket = serverSocket.Accept(); string message = "I am Server Say";//向连接的客户端发送消息SendMessage(clientSocket, message);//创建一个接收客户端消息的线程Thread receiveThread = new Thread(ReceiveClientMessage);//开启线程,参数 clientSocket 为 ReceiveClientMessage 方法的参数receiveThread.Start(clientSocket);}}//接收消息private static void ReceiveClientMessage(object clientSocket){Socket ClientSocket = (Socket)clientSocket;while (true){try{//用于存储接收到的消息byte[] resultByte = new byte[1024]; //通过ClientSocket接收数据int receiveNumber = ClientSocket.Receive( resultByte, resultByte.Length, 0);//获取连接客户端的IP地址和端口string ipPort = ClientSocket.RemoteEndPoint.ToString();string message = Encoding.ASCII.GetString(resultByte, 0, receiveNumber);Console.WriteLine("接收客户端{0}发来的消息{1}", ipPort, message);//服务端接收到客户端发来的消息,再发给客户端SendMessage(ClientSocket, "You Send message is " + message);}catch (Exception ex){Console.WriteLine(ex.Message);Closed(ClientSocket); break;}}}//发送消息的方法private static void SendMessage(Socket clientSocket, string sendMessage){Socket ClientSocket = clientSocket;if (ClientSocket == null) //判断连接的Socket对象是否为空{return;}//将发送的字符串转换为数据包byte[] sendMessageByte = Encoding.UTF8.GetBytes(sendMessage);try{//开始一个异步发送, sendMessageCallBack 为回调方法IAsyncResult asyncSend = ClientSocket.BeginSend(sendMessageByte, 0, sendMessageByte.Length, SocketFlags.None, new AsyncCallback(sendMessageCallBack), ClientSocket);//检测超时,超过五秒表示发送失败bool sendResult = asyncSend.AsyncWaitHandle.WaitOne(5000, true);if (!sendResult){Console.WriteLine("send out time");}}catch{Console.WriteLine("send error");}}//发送消息的毁掉函数private static void sendMessageCallBack(IAsyncResult asyncConnect){Console.WriteLine("服务端已向客户端发送消息");}//关闭private static void Closed(Socket cliSocket){if (cliSocket != null && cliSocket.Connected){cliSocket.Shutdown(SocketShutdown.Both);cliSocket.Close();}cliSocket = null;}}
}
客户端代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;using System.Net;
using System.Net.Sockets;
using System.Threading;//客户端
namespace ClientSocketTest
{class Program{private static byte[] resultByte &#61; new byte[512];private static IPAddress ip;private static Socket clientSocket;static void Main(string[] args){//设定服务器IP地址ip &#61; IPAddress.Parse("127.0.0.1");clientSocket &#61; new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);try{IPEndPoint ipEndpoint &#61; new IPEndPoint(ip, 10000);//建立一个一部的建立连接&#xff0c;当连接建立成功调用 CallBack 方法IAsyncResult result &#61; clientSocket.BeginConnect(ipEndpoint, new AsyncCallback(CallBack), clientSocket);//clientSocket.Connect(new IPEndPoint(ip, 10000));//超时检测&#xff0c;当建立超过 5 秒 还没有连接成功表示超时bool successConnect &#61; result.AsyncWaitHandle.WaitOne(5000, true);if (!successConnect) //判断是否连接成功{//连接失败&#xff0c;关闭Closed(clientSocket);}else{//开启一个接收消息的线程Thread receiveMessageThread &#61; new Thread( ReceiveMessage);//启动线程&#xff0c; clientSocket 为 ReceiveMessage 的参数receiveMessageThread.Start(clientSocket);}Console.WriteLine("连接服务器成功");}catch{Console.WriteLine("连接服务器失败&#xff0c;按任意键退出");return;}//通过clientSocket发送消息,循环3次向服务端发送信息for (int i &#61; 0; i <3; i&#43;&#43;){try{//等待 1 秒Thread.Sleep(1000);string sendMessage &#61; "I&#39;m Client ";//将发送的字符串转换为数据包 SendMessage( clientSocket, sendMessage);//Console.WriteLine("向服务器发送消息 &#xff1a; {0}" &#43; sendMessage);}catch{Closed(clientSocket);break;}}//下面是手动输入数字发送给服务端&#xff0c;当输入为 0 时退出循环int number &#61; 1;while(number !&#61; 0){string str &#61; Console.ReadLine();number &#61; int.Parse(str);string sendMessage &#61; "I&#39;m client send : " &#43; number.ToString();SendMessage( clientSocket, sendMessage);}Console.WriteLine("发送完毕");Console.ReadLine();}private static void CallBack(IAsyncResult asyncConnect){Console.WriteLine("连接成功");}//关闭private static void Closed(Socket cliSocket){// 如果客户端Socket对象不为空&#xff0c;并且为连接状态if (cliSocket !&#61; null && cliSocket.Connected){//关闭SocketcliSocket.Shutdown(SocketShutdown.Both);cliSocket.Close();}cliSocket &#61; null;//将客户端对象赋值为空}//发送消息调用该方法private static void SendMessage( Socket cliSocket, string str){Socket ClientSocket &#61; cliSocket;//将发送的字符串转换为数据包byte[] messageByte &#61; Encoding.UTF8.GetBytes(str);//判断客户端是否连接if (!ClientSocket.Connected){Console.WriteLine("客户端为连接&#xff0c;向服务端发送消息失败");Closed(ClientSocket);return;}try{//开启一个异步发送IAsyncResult asyncSend &#61; clientSocket.BeginSend(messageByte, 0, messageByte.Length, SocketFlags.None, new AsyncCallback(SendMessageCallBack), ClientSocket);//超时检测&#xff0c;超过五秒表示发送失败bool sendResult &#61; asyncSend.AsyncWaitHandle.WaitOne(5000, true);if (!sendResult){Closed(ClientSocket);}}catch{Console.WriteLine("send error");}}//发送消息的回调方法private static void SendMessageCallBack(IAsyncResult asyncConnect){Console.WriteLine("客户端已向服务端发送消息");}//接收消息private static void ReceiveMessage(object cliSocket){//创建一个Socket对象接收要cliSocketSocket ClieSocket &#61; (Socket)cliSocket;//在这个线程中接收服务器发送的数据while (true){if (!ClieSocket.Connected){ClieSocket.Close();break;}try{//通过clientSocket接收数据 //接收数据保存到receiveByte中byte[] receiveByte &#61; new byte[216];//Receive方法会一直等待服务端回发消息,如果没有接收到会一直在这里等待int length &#61; ClieSocket.Receive(receiveByte, receiveByte.Length, 0);if (length <&#61; 0){ClieSocket.Close();break;}if (length > 1){//将接收到的字节转换为字符串string receiveString &#61; Encoding.ASCII.GetString(receiveByte, 0, receiveByte.Length);Console.WriteLine("recive : {0}", receiveString);}}catch{ }}}}
}
分别创建客户端服务端的C#项目&#xff0c;将代码粘贴进去运行即可
运行结果如下所示
&#xff08;1&#xff09;首先运行服务端&#xff1a;
&#xff08;2&#xff09;启动客户端&#xff1a;
服务端监听到客户端的连接后&#xff0c;接收客户端发送的消息
&#xff08;2.1&#xff09;服务端控制台如下所示&#xff1a;
&#xff08;2.2&#xff09;客户端控制台如下所示
&#xff08;2.3&#xff09;在客户端输入数字回车发送给服务端&#xff0c;输入 0 退出
客户端控制台如下
服务端控制台如下