项目 聊天室
1.先創建客戶端
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 using UnityEngine.UI; 5 using System.Net; 6 using System.Net.Sockets; 7 using System.Threading; 8 using System.Text; 9 10 public class WeChatSocket : MonoBehaviour 11 { 12 Socket socket; 13 public InputField InputValue; 14 public Text text; 15 byte[] data = new byte[1024];//接收的容器 16 string message = "";//轉換后的消息 17 // Use this for initialization 18 void Start() 19 { 20 ConnetToSever(); 21 22 } 23 /// <summary> 24 /// 創建Socket并連接服務器IP 25 /// </summary> 26 void ConnetToSever() 27 { 28 socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 29 socket.Connect(new IPEndPoint(IPAddress.Parse("10.0.208.54"), 4567)); 30 Thread t = new Thread(ReceveMessage); 31 t.Start(); 32 } 33 public void ReceveMessage() 34 { 35 36 while (true) 37 { 38 int length = socket.Receive(data); 39 message = Encoding.UTF8.GetString(data, 0, length); 40 } 41 42 } 43 public void SendMessage() 44 { 45 string mess = InputValue.text; 46 InputValue.text = ""; 47 byte[] datas = Encoding.UTF8.GetBytes(mess); 48 socket.Send(datas); 49 } 50 // Update is called once per frame 51 void Update() 52 { 53 if (!string.IsNullOrEmpty(message)) 54 { 55 text.text += message + "\n"; 56 message = ""; 57 } 58 } 59 } 客戶端?
接受消息的時候用容器接受 字節容器byte[];
抽象類 與借口的區別??
1.1鏈接
2.發送(用線程)
?
2.服務器端 ?在vs里面寫
主函數里的代碼:
服務器類里的代碼:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Net.Sockets; 5 using System.Text; 6 using System.Threading; 7 using System.Threading.Tasks; 8 9 namespace 聊天室服務器 10 { 11 /// <summary> 12 /// 消息通訊處理類 接收和發送消息 13 /// </summary> 14 class Client 15 { 16 public Socket socket; 17 public Client(Socket client) 18 { 19 20 socket = client; 21 Thread thread = new Thread(ReceveMessage); 22 thread.Start(); 23 } 24 25 public void ReceveMessage() 26 { 27 while (true) 28 { 29 if (socket.Poll(10, SelectMode.SelectRead))//判斷連接是否中斷 30 { 31 socket.Close(); 32 break; 33 } 34 byte[] data = new byte[1024]; 35 int length = socket.Receive(data); 36 string message = Encoding.UTF8.GetString(data, 0, length); 37 Console.WriteLine("客戶端發來消息是" + message); 38 Program.FenFaMessage(message); 39 } 40 41 42 } 43 public void SendMessage(string str) 44 { 45 byte[] datas = Encoding.UTF8.GetBytes(str); 46 socket.Send(datas); 47 } 48 public bool Connected { 49 50 get { return socket.Connected; } 51 } 52 } 53 } 服務器的分發類的代碼?
?
轉載于:https://www.cnblogs.com/satanj/p/9759090.html
總結
- 上一篇: 为什么在EOS上的DApp对开发人员来说
- 下一篇: CF1060D Social Circl