내 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);
}
}
하지만 여전히 검색을 많이 후 콘솔
TCPClient 샘플 코드를 검색하십시오. 여기에 하나 : http://www.codeincodeblock.com/2013/12/basic-tcp-socket-echo-client-server.html –
@MattSmall 이것은 내가 찾고있는 것이 아닙니다. 내 클라이언트 (윈도우 폰 8.1)가 TcpClient, NetworkStream 등을 모르기 때문에 이것은 중요하지 않습니다. 저는 윈도우 폰에서 콘솔 서버로 통신하는 방법과 그 반대로 통신하는 방법을 알고 싶습니다. –
하지만 서버가 콘솔을 사용하고 있습니다. 내가 여기서 뭔가를 놓치고 있니? 이미 휴대 전화에서 서버로 데이터를 전송하고 있지만 읽는 방법을 모르는 것으로 나타났습니다. –