Unity运用socket传输信息(同步)

客户端:

在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 }
服务端代码

 

 

 

posted @ 2023-10-09 18:19  Jet清远  阅读(211)  评论(0编辑  收藏  举报