Unity网络游戏编程学习(一)
学习《Unity3D网络游戏实战》(第二版)时的学习笔记
Socket通讯流程
简单的示例程序
服务器
使用的是VS的控制台应用
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
//Socket
Socket listenfd = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//Bind
IPAddress ipAdr = IPAddress.Parse("127.0.0.1");
IPEndPoint ipEp = new IPEndPoint(ipAdr,8888);
listenfd.Bind(ipEp);
//Listen
listenfd.Listen(0);
Console.WriteLine("[服务器]启动成功");
while (true) {
//Accept
Socket connfd = listenfd.Accept();
Console.WriteLine("[服务器]Accept");
//Receive
byte[] readBuff = new byte[1024];
int count = connfd.Receive(readBuff);
string readStr = System.Text.Encoding.Default.GetString(readBuff, 0, count);
Console.WriteLine("[服务器接收]" + readStr);
//Send
string feedBack = "接收到" + readStr;
byte[] sendBytes = System.Text.Encoding.Default.GetBytes(feedBack);
connfd.Send(sendBytes);
}
}
客户端
使用的时Unity
public class Echo : MonoBehaviour
{
//定义套接字
Socket socket;
public InputField sendStrInput;
public Text text;
/// <summary>
/// 点击连接按钮
/// </summary>
public void Connection()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Connect("127.0.0.1", 8888);
}
/// <summary>
/// 点击发送按钮
/// </summary>
public void Send()
{
//Send
string sendStr = sendStrInput.text;
byte[] sendBytes = System.Text.Encoding.Default.GetBytes(sendStr);
socket.Send(sendBytes);
Receive();
}
public void Receive()
{
//Receive
byte[] readBuff = new byte[1024];
int count = socket.Receive(readBuff);
string recvStr = System.Text.Encoding.Default.GetString(readBuff, 0, count);
text.text = recvStr;
socket.Close();
}
}
运行效果
注意:这个简单的程序只能进行一次收发,一次过后会报错。
下一篇:Unity网络游戏编程学习(二)