2015-01-14 3 views
0

내 PC의 로컬 콘솔 서버와 Windows phone 8.1의 클라이언트를 사용하여 서버 클라이언트를 만들려고합니다. 문제는 클라이언트에서 들어오는 데이터를 읽는 방법을 모르겠다는 것입니다. 나는 인터넷을 검색하고 serveral Microsoft 튜토리얼을 읽었지 만 서버에서 들어오는 데이터를 읽는 방법을 설명하지는 않습니다. 여기에 내가 가진 것이있다. 창에서버에서 클라이언트로 데이터를 읽고 보내는 방법은 무엇입니까?

클라이언트 전화 8.1 :

private async void tryConnect() 
{ 
    if (connected) 
    { 
     StatusLabel.Text = "Already connected"; 
     return; 
    } 
    try 
    { 
     // serverHostnameString = "127.0.0.1" 
     // serverPort = "1330" 
     StatusLabel.Text = "Trying to connect ..."; 
     serverHost = new HostName(serverHostnameString); 
     // Try to connect to the 
     await clientSocket.ConnectAsync(serverHost, serverPort); 
     connected = true; 
     StatusLabel.Text = "Connection established" + Environment.NewLine; 
    } 
    catch (Exception exception) 
    { 
     // If this is an unknown status, 
     // it means that the error is fatal and retry will likely fail. 
     if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) 
     { 
      throw; 
     } 
     StatusLabel.Text = "Connect failed with error: " + exception.Message; 
     // Could retry the connection, but for this simple example 
     // just close the socket. 

     closing = true; 
     // the Close method is mapped to the C# Dispose 
     clientSocket.Dispose(); 
     clientSocket = null; 
    } 
} 

private async void sendData(string data) 
{ 
    if (!connected) 
    { 
     StatusLabel.Text = "Must be connected to send!"; 
     return; 
    } 
    UInt32 len = 0; // Gets the UTF-8 string length. 

    try 
    { 
     StatusLabel.Text = "Trying to send data ..."; 

     // add a newline to the text to send 
     string sendData = "jo"; 
     DataWriter writer = new DataWriter(clientSocket.OutputStream); 
     len = writer.MeasureString(sendData); // Gets the UTF-8 string length. 

     // Call StoreAsync method to store the data to a backing stream 
     await writer.StoreAsync(); 

     StatusLabel.Text = "Data was sent" + Environment.NewLine; 

     // detach the stream and close it 
     writer.DetachStream(); 
     writer.Dispose(); 
    } 
    catch (Exception exception) 
    { 
     // If this is an unknown status, 
     // it means that the error is fatal and retry will likely fail. 
     if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) 
     { 
      throw; 
     } 

     StatusLabel.Text = "Send data or receive failed with error: " + exception.Message; 
     // Could retry the connection, but for this simple example 
     // just close the socket. 

     closing = true; 
     clientSocket.Dispose(); 
     clientSocket = null; 
     connected = false; 

    } 
} 

그리고 서버 (http://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj150599.aspx에서) :

public class Server 
{ 
    private TcpClient incomingClient; 

    public Server() 
    { 
     TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 1330); 
     listener.Start(); 

     Console.WriteLine("Waiting for connection..."); 
     while (true) 
     { 
      //AcceptTcpClient waits for a connection from the client 
      incomingClient = listener.AcceptTcpClient(); 

      //start a new thread to handle this connection so we can go back to waiting for another client 
      Thread thread = new Thread(HandleClientThread); 
      thread.IsBackground = true; 
      thread.Start(incomingClient); 
     } 
    } 

    private void HandleClientThread(object obj) 
    { 
     TcpClient client = obj as TcpClient; 

     Console.WriteLine("Connection found!"); 
     while (true) 
     { 
      //how to read and send data back? 
     } 
    } 
} 

그것은 서버 인쇄 점에 관해서 '연결 발견!' , 그러나 나는 더 멀리가는 방법을 모른다.

도움을 주시면 감사하겠습니다.

편집 :

지금 내 handleclientthread 방법은 다음과 같습니다

private void HandleClientThread(object obj) 
{ 
    TcpClient client = obj as TcpClient; 
    netStream = client.GetStream(); 
    byte[] rcvBuffer = new byte[500]; // Receive buffer 
    int bytesRcvd; // Received byte count 
    int totalBytesEchoed = 0; 
    Console.WriteLine("Connection found!"); 
    while (true) 
    { 
     while ((bytesRcvd = netStream.Read(rcvBuffer, 0, rcvBuffer.Length)) > 0) 
      { 
       netStream.Write(rcvBuffer, 0, bytesRcvd); 
       totalBytesEchoed += bytesRcvd; 
      } 
      Console.WriteLine(totalBytesEchoed); 
    } 
} 

하지만 여전히 검색을 많이 후 콘솔

+0

TCPClient 샘플 코드를 검색하십시오. 여기에 하나 : http://www.codeincodeblock.com/2013/12/basic-tcp-socket-echo-client-server.html –

+0

@MattSmall 이것은 내가 찾고있는 것이 아닙니다. 내 클라이언트 (윈도우 폰 8.1)가 TcpClient, NetworkStream 등을 모르기 때문에 이것은 중요하지 않습니다. 저는 윈도우 폰에서 콘솔 서버로 통신하는 방법과 그 반대로 통신하는 방법을 알고 싶습니다. –

+0

하지만 서버가 콘솔을 사용하고 있습니다. 내가 여기서 뭔가를 놓치고 있니? 이미 휴대 전화에서 서버로 데이터를 전송하고 있지만 읽는 방법을 모르는 것으로 나타났습니다. –

답변

1

그래서 ...에 바이트를 기록하지 않습니다 인터넷에서 해결책을 찾았습니다.

서버 : 서버에서 읽고 데이터를 전화로 다시 보냅니다.

// method in a new thread, for each connection 
    private void HandleClientThread(object obj) 
    { 
     TcpClient client = obj as TcpClient; 
     netStream = client.GetStream(); 
     Console.WriteLine("Connection found!"); 

     while (true) 
     { 
      // read data 
      byte[] buffer = new byte[1024]; 
      int totalRead = 0; 
      do 
      { 
       int read = client.GetStream().Read(buffer, totalRead, buffer.Length - totalRead); 
       totalRead += read; 
      } while (client.GetStream().DataAvailable); 

      string received = Encoding.ASCII.GetString(buffer, 0, totalRead); 
      Console.WriteLine("\nResponse from client: {0}", received); 

      // do some actions 
      byte[] bytes = Encoding.ASCII.GetBytes(received); 


      // send data back 
      client.GetStream().WriteAsync(bytes, 0, bytes.Length); 
     } 
    } 

전화 (클라이언트) : 휴대 전화에서 메시지를 보내고 서버에서 메시지를 읽을 수 :

private async void sendData(string dataToSend) 
// import for AsBuffer(): using System.Runtime.InteropServices.WindowsRuntime; 
    { 
     if (!connected) 
     { 
      StatusLabel.Text = "Status: Must be connected to send!"; 
      return; 
     } 
     try 
     { 
      byte[] data = GetBytes(dataToSend); 
      IBuffer buffer = data.AsBuffer(); 

      StatusLabel.Text = "Status: Trying to send data ..."; 
      await clientSocket.OutputStream.WriteAsync(buffer); 

      StatusLabel.Text = "Status: Data was sent" + Environment.NewLine; 
     } 
     catch (Exception exception) 
     { 
      if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) 
      { 
       throw; 
      } 

      StatusLabel.Text = "Status: Send data or receive failed with error: " + exception.Message; 
      closing = true; 
      clientSocket.Dispose(); 
      clientSocket = null; 
      connected = false; 
     } 
     readData(); 
    } 

    private async void readData() 
    { 
     StatusLabel.Text = "Trying to receive data ..."; 
     try 
     { 
      IBuffer buffer = new byte[1024].AsBuffer(); 
      await clientSocket.InputStream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.Partial); 
      byte[] result = buffer.ToArray(); 
      StatusLabel.Text = GetString(result); 
     } 
     catch (Exception exception) 
     { 
      if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) 
      { 
       throw; 
      } 

      StatusLabel.Text = "Receive failed with error: " + exception.Message; 
      closing = true; 
      clientSocket.Dispose(); 
      clientSocket = null; 
      connected = false; 
     } 
    } 

'기다리고 clientSocket.InputStream.ReadAsync (버퍼, buffer.Capacity, InputStreamOptions.Partial) '명령은 readData 메소드에서 매우 불분명했습니다. 나는 당신이 새로운 버퍼를 만들어야한다는 것을 몰랐고, ReadAsync-method는 그것을 채 웁니다. 그것을 여기에서 발견 : StreamSocket.InputStreamOptions.ReadAsync hangs when using Wait()

관련 문제