.Net core 使用socket 傳輸數(shù)據(jù)
模擬服務(wù)端
private string TcpServiceControl(string value) ? ? ? ?{ ? ? ? ? ? ?// 1.按照模擬工具上看 先new一個tcp服務(wù) ? ? ? ? ? ?Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ? ? ? ? ? ?//申請端口,綁定ip ? ? ? ? ? ?IPAddress iPAddress = IPAddress.Parse(_appConfig.ApplictionSettings.ControlTcpIP); ? ? ? ? ? ?IPEndPoint iPEndPoint = new IPEndPoint(iPAddress, Convert.ToInt32(_appConfig.ApplictionSettings.ControlTcpPort)); ? ? ? ? ? ?//綁定ip和端口 ? ? ? ? ? ?serverSocket.Bind(iPEndPoint); ? ? ? ? ? ?//開始監(jiān)聽端口 設(shè)置50防止服務(wù)器崩潰,設(shè)置0表示不限制數(shù)量 ? ? ? ? ? ?serverSocket.Listen(0);//傳遞掛起的連接隊(duì)列的最大長度 ? ? ? ? ? ?//接收客戶端信息 程序會暫停 直到由一個客戶端連接過來才會繼續(xù)向下運(yùn)行 ? ? ? ? ? ?Socket clientSocket = serverSocket.Accept();//接收一個客戶端連接,返回一個socket用來和客戶端通訊 ? ? ? ? ? ?//向客戶端發(fā)送一條數(shù)據(jù) ? ? ? ? ? ?byte[] data = System.Text.Encoding.UTF8.GetBytes(value); ? ? ? ? ? ?clientSocket.Send(data); ? ? ? ? ? ?//接收客戶端一條消息 ? ? ? ? ? ?byte[] databuffer = new byte[1024];//接收時先定義一個數(shù)組 ? ? ? ? ? ?int count = clientSocket.Receive(databuffer);//知道數(shù)組中前count個是接收到的數(shù)據(jù) ? ? ? ? ? ?String hex = Encoding.ASCII.GetString(databuffer, 0, count); ? ? ? ? ? ?//string msgREceive = System.Text.Encoding.UTF8.GetString(databuffer, 0, count); ? ? ? ? ? ?//Console.WriteLine(msgREceive); ? ? ? ? ? ?//Console.ReadKey();//程序終止的太快,方便觀察輸出 ? ? ? ? ? ?//關(guān)閉服務(wù)器端 ? ? ? ? ? ?clientSocket.Close();//關(guān)閉與客戶端的連接 ? ? ? ? ? ?serverSocket.Close();//關(guān)閉服務(wù)器自身的連接 ? ? ? ? ? ?return hex; ? ? ? ?}
模擬客戶端
private static void NewMethod() ? ? ? ?{ ? ? ? ? ? ?// 1.按照模擬工具上看 先new一個tcp服務(wù) ? ? ? ? ? ?//Parse將字符串轉(zhuǎn)換為IP地址類型 ? ? ? ? ? ?IPAddress myIP = IPAddress.Parse("192.168.88.1"); ? ? ? ? ? ?//構(gòu)造一個TcpClient類對象,TCP客戶端 ? ? ? ? ? ?TcpClient client = new TcpClient(); ? ? ? ? ? ?//與TCP服務(wù)器連接 ? ? ? ? ? ?client.Connect(myIP, 10067); ? ? ? ? ? ?Console.WriteLine("服務(wù)器已經(jīng)連接...請輸入對話內(nèi)容..."); ? ? ? ? ? ?//創(chuàng)建網(wǎng)絡(luò)流,獲取數(shù)據(jù)流 ? ? ? ? ? ?NetworkStream stream = client.GetStream(); ? ? ? ? ? ?//讀數(shù)據(jù)流對象 ? ? ? ? ? ?StreamReader sr = new StreamReader(stream); ? ? ? ? ? ?//寫數(shù)據(jù)流對象 ? ? ? ? ? ?StreamWriter sw = new StreamWriter(stream); ? ? ? ? ? ?while (true) ? ? ? ? ? ?{ ? ? ? ? ? ? ? ?string msg = Console.ReadLine(); ? ? ? ? ? ? ? ?sw.WriteLine(msg); ? ? ? ? ? ? ? ?sw.Flush(); ? ? ? ? ? ? //刷新流 ? ? ? ? ? ? ? ?Console.WriteLine("服務(wù)器:" + sr.ReadLine()); ? ? ? ? ? ?} ? ? ? ? ? ?client.Close(); ? ? ? ? ? ?Console.Read(); ? ? ? ? ? ?// 2.輸入的數(shù)據(jù)轉(zhuǎn)化為 16 進(jìn)制傳輸 ? ? ? ?}
?
鏈接:https://www.dianjilingqu.com/607194.html