我对tcp / ip比较新,所以我希望我的代码不会让人感到尴尬。我有一个tcp监听器/客户端有2个问题。
我不确定如何将这些功能实现到我当前的代码库中,并且正在寻求最佳实践/想法。以前的答案我发现所有人似乎都在使用旧信息或不同类别。 听众只需连接到一个客户端就可以了。
的TCPListener:
"
的TcpClient:
public async Task Start() {
tcpListener = new TcpListener(_iPAddress, _listeningPort);
tcpListener.Start(1);
//Debug.Log("Listening on port " + _listeningPort);
try {
tcpClient = await tcpListener.AcceptTcpClientAsync();
clientConnected = true;
//Debug.Log("Got connection request from " + tcpClient.Client.RemoteEndPoint.ToString());
} catch (Exception exp) {
Debug.Log(exp.ToString());
}
}
public async void GetData(Action<Ball> callback) {
Ball ball;
try {
using (var networkStream = tcpClient.GetStream())
using (var reader = new StreamReader(networkStream))
using (var writer = new StreamWriter(networkStream)) {
writer.AutoFlush = true;
while (gameInPlay) {
string dataFromClient = await reader.ReadLineAsync();
ball = Newtonsoft.Json.JsonConvert.DeserializeObject<Ball>(dataFromClient);
ball = BallConfiguration.AttachBallNumber(ball);
if (registeredBalls.Any(regEpc => regEpc == ball.Epc)) {
callback(ball);
}
}
}
} catch (NullReferenceException e) {
Debug.Log(e);
} finally {
tcpListener.Stop();
clientConnected = false;
}
}