客戶端: 在UGUI中創建兩個Button,一個是連接伺服器,一個是發送消息的按鈕,分別綁定Connection和SendMessage兩個函數 並且創建一個InputField和一個Text文本,Text文本用於顯示伺服器回傳的消息,InputField用於輸入要發送的消息 以下是代碼: 1 us ...
客戶端:
在UGUI中創建兩個Button,一個是連接伺服器,一個是發送消息的按鈕,分別綁定Connection和SendMessage兩個函數
並且創建一個InputField和一個Text文本,Text文本用於顯示伺服器回傳的消息,InputField用於輸入要發送的消息
以下是代碼:
1 using System.Collections; 2 using System.Collections.Generic; 3 using System.Net.Sockets; 4 using UnityEngine; 5 using UnityEngine.UI; 6 7 public class Client : MonoBehaviour 8 { 9 Socket client; 10 public InputField inputField; 11 public Text text; 12 13 public void Connection() 14 { 15 client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 16 client.Connect("127.0.0.1",10086); 17 } 18 19 public void SendMessage() 20 { 21 //發送數據報文 22 string messageToServer = inputField.text; 23 byte[] sendMessage = System.Text.Encoding.UTF8.GetBytes(messageToServer); 24 client.Send(sendMessage); 25 //接收數據報文 26 byte[] messageToClient = new byte[1024]; 27 int count = client.Receive(messageToClient); 28 string messageFromServer = System.Text.Encoding.UTF8.GetString(messageToClient,0,count); 29 text.text = messageFromServer; 30 client.Close(); 31 } 32 }客戶端代碼
服務端:
服務端採用VS提供的WFP視窗做服務端,可以添加一些控制項來美化GUI界面
以下是我做的一個簡單的GUI界面
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Net; 5 using System.Net.Sockets; 6 using System.Reflection.Emit; 7 using System.Text; 8 using System.Threading.Tasks; 9 10 namespace 同步聊天Server 11 { 12 public static class Server 13 { 14 public static string showMessag=""; 15 public static void OpenServer() 16 { 17 Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 18 IPAddress ip = IPAddress.Parse("127.0.0.1"); 19 IPEndPoint serverAddress = new IPEndPoint(ip, 10086); 20 server.Bind(serverAddress); 21 server.Listen(10);//如果為零,則表示不受限制 22 showMessag += "伺服器啟動成功"; 23 Socket oneToOnePort = server.Accept(); 24 byte[] messageFromClient = new byte[1024]; 25 int count = oneToOnePort.Receive(messageFromClient); 26 string message = Encoding.UTF8.GetString(messageFromClient, 0, count); 27 showMessag += message; 28 byte[] messageToClient = Encoding.UTF8.GetBytes(message); 29 oneToOnePort.Send(messageToClient); 30 } 31 32 } 33 }服務端代碼
翻譯
搜索
複製