標籤:res threading int string system 開始 lin text 資料
我在之前的socket通訊的基礎上做了一點改進,使用多線程來使用,程式更加簡潔實用。不足之處請指教哦!
話不多說,之前的隨筆也有介紹,直接上代碼啦!
服務端socket(serverSocket):
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Net; 7 using System.Threading; 8 using System.Net.Sockets; 9 10 namespace serverSocketTest611 {12 class Program13 {14 static Socket serverSocket;15 static int port = 2723;16 17 static void Main(string[] args)18 {19 Console.WriteLine("服務端:");20 21 //執行個體化socket類22 serverSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);23 IPAddress ip = IPAddress.Parse("173.168.5.15");24 //標識網路地址25 EndPoint point = new IPEndPoint(ip,port);26 //綁定IP地址和連接埠號碼27 serverSocket.Bind(point);28 29 //開始監聽用戶端的串連30 serverSocket.Listen(10);31 Console.WriteLine("等待用戶端串連...");32 33 Thread myThread = new Thread(ListenClientSocket);34 myThread.Start();35 36 37 Console.ReadKey();38 39 40 41 }42 43 /// <summary>44 /// 監聽用戶端45 /// </summary>46 static void ListenClientSocket()47 {48 while (true)49 {50 Socket clientSocket = serverSocket.Accept();//接受用戶端的串連51 Console.WriteLine("用戶端串連成功");52 53 string message = "2017,新的開始,新年快樂!加油!繼續努力!!!";54 byte[] data=Encoding.UTF8.GetBytes(message);55 clientSocket.Send(data);56 57 Thread receive = new Thread(receiveSocket);//receiveSocket 被傳遞的方法58 receive.Start(clientSocket); //clientSocket 被傳遞的參數59 }60 61 }62 63 /// <summary>64 /// 接收來自用戶端的訊息65 /// </summary>66 static void receiveSocket(object clientSocket) ////// 這裡的參數是線程中的參數,參數類型必須是object類型67 {68 Socket myClientSocket = (Socket)clientSocket; //// 將object類型的參數轉換成socket類型 使用參數來啟動線程,執行後面的代碼69 while (true)70 {71 byte[] data=new byte[1024];72 int length = myClientSocket.Receive(data);73 string message=Encoding.UTF8.GetString(data,0,length);74 Console.WriteLine("接收到來自用戶端的訊息:"+message);75 76 77 }78 }79 }80 }
用戶端的代碼基本沒變~
用戶端socket(clientSocket):
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Net;using System.Threading;using System.Net.Sockets;namespace clientSocketTest6{ class Program { static Socket clientSocket; static int port = 2723; static void Main(string[] args) { Console.WriteLine("用戶端:"); //實力化一個socket類 clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ip = IPAddress.Parse("173.168.5.15"); //用戶端請求與服務端的串連 clientSocket.Connect(ip, port); Console.WriteLine("伺服器串連成功."); //接受資料 byte[] data = new byte[1024]; int length = clientSocket.Receive(data); string message = Encoding.UTF8.GetString(data, 0, length); Console.WriteLine("接受到來自服務端的祝福:" + message); //向服務端發送數居 for (int i = 0; i < 10; i++) { Thread.Sleep(2000);//使該線程暫停(休眠)2s string message2 = "Fighting!!"; //可以寫成string message2=Console.ReadLine(); byte[] data2 = Encoding.UTF8.GetBytes(message2); clientSocket.Send(data2); Console.WriteLine("向服務端發送訊息:{0}",message2); } Console.ReadKey(); } }}
C#socket通訊-----多線程