TCP 클라이언트를 만들었지 만 연결이 잘되었지만 연결을 닫지 않고 서버로부터 메시지를받는 방법이 약간 혼란 스럽습니까?내 프로그램이 TCP 연결로 멈추는 것을 막는 방법 C#
현재 나의 접근 방식은 네트워크 스트림 읽기 방법을 통해 공동 루틴을 실행하는 것이었지만 내 프로그램이 멈추었 기 때문에 잘못된 접근 방식으로 인해이를 수정하는 방법을 잘 모릅니다.
연결을 유지하고 메시지가 서버에서 도착할 때 읽을 수 있습니다.
public int Recieve(byte[] readBuffer)
{
if (!IsConnected)
return -1; //-1 signifies an error aka we are disconnected
try
{
// NetworkStream is from TcpClient.GetStream()
bytesRead = _networkStream.Read(readBuffer, 0, readBuffer.Length);
}
catch (Exception e)
{
IsConnected = false;
Debug.Log(e);
bytesRead = -1;
}
return bytesRead;
}
어떻게 난 내 프로그램을 잠금이 발생하지 않도록 않습니다
// the idea is to run a coroutine for recieving messages
private IEnumerator<float> _RunTCPSocket()
{
int timer = DateTime.Now.Second;
byte[] readBuffer = new byte[1024];
while (SocketManager.IsConnected)
{
// this is the keep alive packets to server to prevent timeout on server side
if (DateTime.Now.Second - timer > KeepAliveRate)
{
Debug.Log("Sending");
timer = DateTime.Now.Second;
SocketManager.Send(null);
}
int msgLength = SocketManager.Recieve(readBuffer);
if (msgLength > 0)
Debug.Log(Encoding.ASCII.GetString(readBuffer, 0, msgLength));
yield return Timing.WaitForOneFrame;
}
}
이 수신 방법에 대한 코드는 다음과 같습니다
이 내가 현재 설정이 무엇인가?
다른 스레드에서 네트워크 작업을해야합니다. 비동기 기능을 사용하여 읽기, 보내기 및 연결하고 네트워크를 청취하거나 이러한 기능은 무언가 (오류/성공)가 발생할 때까지 차단됩니다. – Programmer
BackgroundWorker를 사용해야합니다. https://msdn.microsoft.com/es-es/library/cc221403(v=vs.95).aspx –
흠, 비동기 메서드를 살펴 봤지만 예제가 없습니다. 유일한 TCP 클라이언트 예제입니다. 그들은 동기식이었다. – Sir