我正在使用Unity 5.5.4。
我已经创建了一个TCP服务器和一个客户端监听器。
以下是我如何连接到客户端上的服务器:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Net.Sockets;
using System.IO;
using System;
using System.Text.RegularExpressions;
using UnityEngine.SceneManagement;
using Newtonsoft.Json;
using System.Linq;
using System.Threading;
public class ClientWorldServer : MonoBehaviour {
public bool socketReady;
public static TcpClient socket;
public static NetworkStream stream;
public static StreamWriter writer;
public static StreamReader reader;
public void ConnectToWorldServer()
{
if (socketReady)
{
return;
}
//Default host and port values;
string host = "127.0.0.1";
int port = 8080;
//ClientLoginServer ClientLoginServer = new ClientLoginServer();
try
{
socket = new TcpClient(host, port);
stream = socket.GetStream();
socket.NoDelay = true;
writer = new StreamWriter(stream);
reader = new StreamReader(stream);
socketReady = true;
//Preserve the connection to worldserver thrue scenes
DontDestroyOnLoad(worldserverConnection);
}
catch (Exception e)
{
Debug.Log("Socket error : " + e.Message);
}
}
}
在同一个ClientWorldServer
课程中,我是如何检查可用数据的:
// Update is called once per frame
void Update () {
if (socketReady)
{
if (stream.DataAvailable)
{
string data = reader.ReadLine();
if (data != null)
{
OnIncomingData(data);
}
}
}
}
对于那些不熟悉Unity void Update()
的人,每帧调用一次。它非常像无尽的while
循环。
这是我的OnIncomingData
功能:
private void OnIncomingData(string data)
{
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
JsonData json = JsonConvert.DeserializeObject<JsonData>(data);
string prefix = json.header.Substring(0, 2);
if (prefix != "0x")
{
Debug.Log("Unknown packet: " + data + "\n");
}
else
{
string header = json.header.Substring(2);
int conId = json.connectionId;
//Debug.Log("Header:" + header);
switch (header)
{
default:
Debug.Log("Unknown packet: " + data + "\n");
break;
case "000":
Debug.Log("Empty header received: " + json.header + "\n");
break;
case "001":
if(connectionId == 0)
{
connectionId = conId;
Debug.Log("Connection ID: " + connectionId + "\n");
}
break;
case "004":
DisplayCharacterSelects(json.data, connectionId);
break;
case "005":
PlayerSpawner playerSpawner = new PlayerSpawner();
playerSpawner.SpawnPlayer(json.data, conId);
break;
case "006":
PlayerSpawner OnliePlayersSpawner = new PlayerSpawner();
OnliePlayersSpawner.SpawnOnlinePlayers(json.data);
break;
case "007":
CharacterLogout(json.data);
break;
case "008":
Character character = new Character();
character.updateCharacterPosition(json.data, conId);
break;
case "009":
Character characterR = new Character();
characterR.updateCharacterRotation(json.data, conId);
break;
}
Debug.Log("World Server: " + data);
}
}).Start();
}
在我所做的检查中,我可以向您保证服务器不会减慢发送数据的过程。客户在某种程度上放慢了阅读速度。重要的是要说当我们移动到服务器时我发送玩家位置然后服务器响应所有连接的客户端通知他们某些玩家改变了它的位置。这意味着每1秒钟会发出很多请求。
也许我没有采取最好的方法,或者我有一个新手的错误,但这是我第一次接触TCP。
您是否看到为什么在客户端可以减慢许多请求中的数据处理速度的原因,如果是这样,我该如何解决?