2017-01-19 6 views
0

TCP를 통해 수신 대기 할 때 데이터를 전송할 수 없습니다. 들어오는 모든 연결을 수신해야하며 필요할 때마다 데이터를 보내야합니다. 내 서버 코드가 시작됩니다. 때 프로그램의 부하를 듣고,하지만 난 데이터를 보내려고 할 때이 오류 제공합니다 : 여기TCP- 서버로 수신 할 때 데이터를 보낼 수 없습니다.

"Only one usage of each socket address (protocol/network address/port) is normally permitted (typically under load)."

그리고 내 코드입니다 : 어떤 도움 apprecitated됩니다

public void Send(object sender, System.EventArgs e) 
    { 
     String str = "08"; 
     String str2 = "4213"; 
     String CRCvalue = CRC("08" + str2); 
     String str3 = str2 + CRCvalue; 
     Connect("localhost", "hello localhost " + Guid.NewGuid()); 
    } 
    static void Connect(String server, String message) 
    { 

      try 
       {    
         Int32 port = 2101; 
         TcpClient client = new TcpClient(server, port);    
         Byte[] data = System.Text.Encoding.ASCII.GetBytes(message); 
         NetworkStream stream = client.GetStream(); 

         // Send the message to the connected TcpServer. 
         stream.Write(data, 0, data.Length); 
         System.Diagnostics.Debug.WriteLine("Sent");   
         stream.Close(); 
         client.Close(); 
       } 
      catch (ArgumentNullException e) 
      { 
       System.Diagnostics.Debug.WriteLine("ArgumentNullException: {0}", e); 
      } 
      catch (SocketException e) 
      { 
       System.Diagnostics.Debug.WriteLine("SocketException: {0}", e); 
      }} 
     protected override void OnLoad(EventArgs e) 
    { 
     CreateServer(); 
    } 
     private static void CreateServer() 
     { 
      var tcp = new TcpListener(System.Net.IPAddress.Any,25565); 
      tcp.Start(); 



      var listeningThread = new Thread(() => 
      { 
       while (true) 
       { 
        var tcpClient = tcp.AcceptTcpClient(); 
        ThreadPool.QueueUserWorkItem(param => 
        { 
         NetworkStream stream = tcpClient.GetStream(); 
         string incomming; 
         byte[] bytes = new byte[1024]; 
         int i = stream.Read(bytes, 0, bytes.Length); 
         incomming = System.Text.Encoding.ASCII.GetString(bytes, 0, i); 
         System.Diagnostics.Debug.WriteLine(incomming); 
         tcpClient.Close(); 
        }, null); 
       } 
      }); 

합니다.

+1

"데이터 전송"코드를 표시 할 수 있습니까? 질문에있는 코드는 메시지를 보내고 일부 데이터를 수신하는 방법 만 보여줍니다. Connect()는 실제로 어디에 사용됩니까? Connect() 메서드 또는 CreateServer() 메서드에서 예외가 throw되는 위치를 명시하지 않았습니까? – Ben

+0

사이드 노트 : TCP는 메시징이 아닌 바이트 방향 (각 방향)입니다. 'Read' 호출에서 얻은 결과가 다른 끝에'Write' 호출과 1-1로 일치한다는 보장은 없습니다. –

+0

지금 추가했습니다. –

답변

0

예외는 동일한 서버 소켓을 두 번 이상 열려고 시도한다는 것을 나타냅니다. 양식 닫을 때 TcpListener을 닫고 청취 스레드에 참여해야합니다. tcp 리스너를 관리하는 싱글 톤 서비스를 사용할 수도 있습니다 (또는 정적 필드를 지정하고 필드가 설정되지 않은 경우에만 리스너를 생성 할 수 있습니다).