直接上代碼 服務端: using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using Sy ...
直接上代碼
服務端:
using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; namespace SocketServer { /// <summary> /// MainWindow.xaml 的交互邏輯 /// </summary> public partial class MainWindow : Window { private Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); private byte[] _result = new byte[1024]; public MainWindow() { InitializeComponent(); } private void ButtonBase_OnClick(object sender, RoutedEventArgs e) { SocketService(); } public void SocketService() { textBlock.Text += ("服務端已啟動"); var host = "127.0.0.1"; var port = 5000; _socket.Bind(new IPEndPoint(IPAddress.Parse(host), port)); _socket.Listen(10); // 設定最多10個排隊連接請求 Task.Run(ListenClientConnect); } private void ListenClientConnect() { while (true) { var clientSocket = _socket.Accept(); clientSocket.Send(Encoding.UTF8.GetBytes("我是伺服器")); var receiveThread = new Thread(ReceiveMessage); receiveThread.Start(clientSocket); } } private void ReceiveMessage(object clientSocket) { Socket myClientSocket = (Socket)clientSocket; while (true) { try { //通過clientSocket接收數據 int receiveNumber = myClientSocket.Receive(_result); if (receiveNumber == 0) return; Application.Current.Dispatcher.Invoke(() => { textBlock.Text += string.Format("接收客戶端{0} 的消息:{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(_result, 0, receiveNumber)); }); //給Client端返回信息 string sendStr = "已成功接到您發送的消息"; byte[] bs = Encoding.UTF8.GetBytes(sendStr);//Encoding.UTF8.GetBytes()不然中文會亂碼 myClientSocket.Send(bs, bs.Length, 0); //返回信息給客戶端 //myClientSocket.Close(); //發送完數據關閉Socket並釋放資源//長連接的話就不關閉 //Console.ReadLine(); } catch (Exception ex) { Application.Current.Dispatcher.Invoke(() => { textBlock.Text += (ex.Message); }); myClientSocket.Close();//關閉Socket並釋放資源 //myClientSocket.Shutdown(SocketShutdown.Both);//禁止發送和上傳 break; } } } } }
客戶端:
using System; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Windows; namespace SocketClient { /// <summary> /// MainWindow.xaml 的交互邏輯 /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void ButtonBase_OnClick(object sender, RoutedEventArgs e) { ShotLink("321"); // LongLink(); } /// <summary> /// 短連接,最後調用Close釋放資源 /// </summary> /// <param name="input"></param> private void ShotLink(string input) { //設定伺服器IP地址 IPAddress ip = IPAddress.Parse("127.0.0.1"); Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { clientSocket.Connect(new IPEndPoint(ip, 5000)); //配置伺服器IP與埠 textBlock.Text += ("連接伺服器成功"); } catch { textBlock.Text += ("連接伺服器失敗!"); return; } string sendMessage = "你好";//發送到服務端的內容 clientSocket.Send(Encoding.UTF8.GetBytes(sendMessage));//向伺服器發送數據,需要發送中文則需要使用Encoding.UTF8.GetBytes(),否則會亂碼 textBlock.Text += ("向伺服器發送消息:" + sendMessage); //接受從伺服器返回的信息 string recvStr = ""; byte[] recvBytes = new byte[1024]; int bytes; bytes = clientSocket.Receive(recvBytes, recvBytes.Length, 0); //從伺服器端接受返回信息 recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes); textBlock.Text += string.Format("服務端發來消息:{0}", recvStr);//回顯伺服器的返回信息 //每次完成通信後,關閉連接並釋放資源 clientSocket.Close(); Console.ReadLine(); } /// <summary> /// 長連接不調用Close釋放資源 /// </summary> private void LongLink() { //設定伺服器IP地址 IPAddress ip = IPAddress.Parse("127.0.0.1"); Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { clientSocket.Connect(new IPEndPoint(ip, 5000)); //配置伺服器IP與埠 textBlock.Text += ("連接伺服器成功"); } catch { textBlock.Text += ("連接伺服器失敗"); return; } //迴圈讀取輸入數據 while (true) { textBlock.Text += ("請輸入"); string sentstr = "123"; SentMsg(sentstr, clientSocket); Thread.Sleep(5000); } } /// <summary> /// 長連接,不釋放資源 /// </summary> /// <param name="sentstr"></param> /// <param name="clientSocket"></param> private void SentMsg(string sentstr, Socket clientSocket) { string sendMessage = "你好";//發送到服務端的內容 sendMessage = sentstr;//發送到服務端的內容 //向伺服器發送數據,需要發送中文則需要使用Encoding.UTF8.GetBytes(),否則會亂碼 clientSocket.Send(Encoding.UTF8.GetBytes(sendMessage)); textBlock.Text += ("向伺服器發送消息:" + sendMessage); //接受從伺服器返回的信息 string recvStr = ""; byte[] recvBytes = new byte[1024]; int bytes; bytes = clientSocket.Receive(recvBytes, recvBytes.Length, 0); //從伺服器端接受返回信息 recvStr += Encoding.UTF8.GetString(recvBytes, 0, bytes); textBlock.Text += string.Format("服務端發來消息:{0}", recvStr); //回顯伺服器的返回信息 //clientSocket.Close();//關閉連接並釋放資源//如果是長連接,註釋掉close } } }