1、介绍
学习《Unity网络游戏实战》第一章,网络游戏的开端:Echo。
客户端开发环境:Windows10,Unity2019,C#
服务端开发环境:Centos7, Python
2、客户端
客户端界面如下:
由简单的inputfield和两个button组成。
Connect按钮用于连接服务器。Send用于发送数据。
Echo.cs
using UnityEngine;
using UnityEngine.UI;
using System.Net;
using System.Net.Sockets;
public class Echo : MonoBehaviour
{
public InputField inputField_ip;
public InputField inputField_port;
public InputField inputField_msg;
private IPAddress ip;
private int port;
private bool socketConnected = false;
// 定义服务器套接字
Socket socket;
// 输入ip
public void InputIP(string _ip)
{
ip = IPAddress.Parse(inputField_ip.text);
}
// 输入port
public void InputPort(string _port)
{
port = int.Parse(inputField_port.text);
}
public void OnButtonConnectClick()
{
try{
socket.Connect(ip, port);
}
catch(SocketException)
{
Debug.Log("Connect Failed!");
socketConnected = false;
return;
}
socketConnected = true;
Debug.Log("Connect Server.");
}
public void OnButtonSendClick()
{
if (!socketConnected)
{
Debug.Log("Socket not connected.");
return;
}
string sendMsg = inputField_msg.text;
if (sendMsg == "")
{
Debug.Log("message not null");
return;
}
// 发送数据
byte[] sendBytes = System.Text.Encoding.Default.GetBytes(sendMsg);
socket.Send(sendBytes);
}
void Start()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
void Update()
{
if (!socketConnected)
return;
// 接收数据
byte[] recvBuff = new byte[1024];
if (socket.Available > 0)
{
// 实际接收到的长度
int count = socket.Receive(recvBuff);
if (count <= 0)
{
Debug.Log("receive 0 msg, error");
socketConnected = false;
socket.Close();
return;
}
string recvMsg = System.Text.Encoding.UTF8.GetString(recvBuff, 0, count);
Debug.Log("Receive message = " + recvMsg);
}
}
}
脚本要挂载在Canvas下:
3、服务端
服务端使用Python,代码:
import socket
# server socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ("127.0.0.1", 8888)
server.bind(server_address)
server.listen(1)
print "Server Start."
while True:
connection, client_address = server.accept()
print "client connected: ", client_address
while True:
try:
data = connection.recv(1024)
print "receive data : ", data
if data:
connection.sendall("receive message: " + data)
else:
connection.close()
break
except socket.error:
connection.close()
server_address 中第一个为ip,第二个为端口。ip和port根据情况写就行。
4、运行效果
服务端程序挂载腾讯云上跑,客户端连接之后可以正常通讯。
5、结语
Echo程序只是一个作为网络通讯程序开端。后续随着书本深入下去,最后是做一个多人的实战的坦克大战项目。希望能坚持到哪个时候 = =!。