本文主要记录c#下TCPsocket编程的方法。 代码来源:https://blog.csdn.net/yangwohenmai1/article/details/92589072
长连接和短连接 (以下来源于上面的链接) 对于Socket来说,链接类型一般分为长连接和短连接。
长连接和短连接在程序上基本没有区别,区别是短连接每次发送完消息都要调用Close()方法来释放资源,而长连接则不调用Close()方法,从而保持持续不断的通信功能。
服务器端代码 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 using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;using System.Threading.Tasks;namespace SocketServer { class Program { static Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); private static byte [] result = new byte [1024 ]; static void Main (string [] args ) { SocketServie(); } public static void SocketServie ( ) { Console.WriteLine("服务端已启动" ); string host = "127.0.0.1" ; int port = 81 ; socket.Bind(new IPEndPoint(IPAddress.Parse(host), port)); socket.Listen(100 ); Thread myThread = new Thread(ListenClientConnect); myThread.Start(); Console.ReadLine(); } private static void ListenClientConnect ( ) { while (true ) { Socket clientSocket = socket.Accept(); clientSocket.Send(Encoding.UTF8.GetBytes("我是服务器" )); Thread receiveThread = new Thread(ReceiveMessage); receiveThread.Start(clientSocket); } } private static void ReceiveMessage (object clientSocket ) { Socket myClientSocket = (Socket)clientSocket; while (true ) { try { int receiveNumber = myClientSocket.Receive(result); if (receiveNumber == 0 ) return ; Console.WriteLine("接收客户端{0} 的消息:{1}" , myClientSocket.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(result, 0 , receiveNumber)); } catch (Exception ex) { Console.WriteLine(ex.Message); myClientSocket.Close(); break ; } } } } }
这里需要注意的是“给Client端返回信息”,若Client已经关闭,会进入catch部分;而myClientSocket.Shutdown这句话会报错,因此注释。 此外,这里的ip地址:127.0.0.1代表本机;端口可以随意取(80除外,这代表HTTP) 服务器端先开始运行,并进入监听状态;客户端在此期间运行并寻求连接,然后连接成立。 第一行的ProtocolType.Tcp表示TCP协议。
客户端代码 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 using System;using System.Collections.Generic;using System.Linq;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading.Tasks;namespace SocketClient { class Program { static void Main (string [] args ) { int port = 81 ; shotlink("" ,port); } public static void shotlink (string input,int port ) { IPAddress ip = IPAddress.Parse("127.0.0.1" ); Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { clientSocket.Connect(new IPEndPoint(ip, port)); Console.WriteLine("连接服务器成功" ); } catch { Console.WriteLine("连接服务器失败,请按回车键退出!" ); Console.ReadLine(); return ; } string sendMessage = "你好" ; clientSocket.Send(Encoding.UTF8.GetBytes(sendMessage)); Console.WriteLine("向服务器发送消息:" + sendMessage); string recvStr = "" ; byte [] recvBytes = new byte [1024 ]; int bytes; bytes = clientSocket.Receive(recvBytes, recvBytes.Length, 0 ); recvStr += Encoding.UTF8.GetString(recvBytes, 0 , bytes); Console.WriteLine("服务端发来消息:{0}" , recvStr); clientSocket.Close(); Console.ReadLine(); } public static void longlink (int port ) { IPAddress ip = IPAddress.Parse("127.0.0.1" ); Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { clientSocket.Connect(new IPEndPoint(ip, port)); Console.WriteLine("连接服务器成功" ); } catch { Console.WriteLine("连接服务器失败,请按回车键退出!" ); Console.ReadLine(); return ; } while (true ) { Console.WriteLine("请输入" ); string sentstr = Console.ReadLine(); SentMsg(sentstr, clientSocket); } } public static void SentMsg (string sentstr, Socket clientSocket ) { string sendMessage = "你好" ; sendMessage = sentstr; clientSocket.Send(Encoding.UTF8.GetBytes(sendMessage)); Console.WriteLine("向服务器发送消息:" + sendMessage); string recvStr = "" ; byte [] recvBytes = new byte [1024 ]; int bytes; bytes = clientSocket.Receive(recvBytes, recvBytes.Length, 0 ); recvStr += Encoding.UTF8.GetString(recvBytes, 0 , bytes); Console.WriteLine("服务端发来消息:{0}" , recvStr); } } }
这里需要注意的是:ip地址和端口号需要和服务器端保持一致。而且一定要服务器端先运行,客户端后运行。 Socket类的构造函数的参数中,ProtocolType.Tcp表示TCP协议。