using(connectedTcpClient = tcpListener.AcceptTcpClient())
这就是杀死连接的原因。如何保持此连接打开?
添加另一个
while(true)
连接后,我将无法完成任务。以及在使用语句之后执行while循环完成。
private void ListenForIncommingRequests()
{
try
{
// Create listener on localhost port 8052.
localAddr = IPAddress.Parse(IPadrr);
Debug.Log(localAddr);
tcpListener = new TcpListener(localAddr, port);
Debug.Log("Before Init tcplistern");
tcpListener.Start();
Debug.Log("Server is listening");
Byte[] dataRecieved = new Byte[SEND_RECIEVE_COUNT];
while (true)
{
using (connectedTcpClient = tcpListener.AcceptTcpClient())
{
Debug.Log("Accepted TCP Client");
// Get a stream object for reading
using (NetworkStream stream = connectedTcpClient.GetStream())
{
int length;
Debug.Log("Accepted Stream");
// Read incomming stream into byte arrary.
while ((length = stream.Read(dataRecieved, 0, dataRecieved.Length)) != 0)
{
Debug.Log("receiving Loop lengt: " + length);
counterReceived++;
//Get Message length with first message
if (messageLength == 0)
{
messageLength = System.BitConverter.ToInt32(dataRecieved, 0);
data = new byte[messageLength];
messageJunks = messageLength / SEND_RECIEVE_COUNT;
restMessage = messageLength % SEND_RECIEVE_COUNT;
junkCounter = 0;
}
else
{
if (junkCounter < messageJunks)
{
Array.Copy(dataRecieved, 0, data, junkCounter * SEND_RECIEVE_COUNT, SEND_RECIEVE_COUNT);
junkCounter++;
}
else
{
Array.Copy(dataRecieved, 0, data, junkCounter * SEND_RECIEVE_COUNT, restMessage);
//Whole Message recieved, reset Message length
messageLength = 0;
readyToDisplay = true;
Debug.Log("ImageLengthResetteed");
}
}
}
}
}
}
}
catch (Exception socketException)
{
Debug.Log("SocketException " + socketException.ToString());
}
}
客户端打开具有以下功能的发送线程,其中socketConnection在客户端的接收线程上进行全局初始化:
private void sendData(byte[] data)
{
try
{
//socketConnection = new TcpClient(IPadrr, port);
using (NetworkStream stream = socketConnection.GetStream())
{
//Prepare the Length Array and send first
byte[] dataLength = BitConverter.GetBytes(data.Length);
int packagesSend = 0;
int numberPackages = data.Length / SEND_RECIEVE_COUNT;
if (stream.CanWrite)
{
for (counter = 0; counter <= data.Length; counter += SEND_RECIEVE_COUNT)
{
if (counter == 0)
{
stream.Write(dataLength, 0, dataLength.Length);
}
if (packagesSend < numberPackages)
{
stream.Write(data, counter, SEND_RECIEVE_COUNT);
Thread.Sleep(20);
packagesSend++;
}
else
{
stream.Write(data, counter, data.Length % SEND_RECIEVE_COUNT);
Debug.Log("FINDISCHD");
}
}
}
}
}
catch (Exception err)
{
print(err.ToString());
}
}
很高兴为您提供帮助!
答案 0 :(得分:0)
问题出在客户端。我初始化了
# [1] 1 2 7 8
现在在NetworkStream stream;
的同一函数中全局初始化。