0

我正在尝试为 windows phone 7 创建一个应用程序,它充当客户端并将请求发送到用 Java 编写的服务器。客户端应该发送请求,并等待来自服务器的答复。我的问题是我似乎无法与服务器正常通信。当我尝试在一个简单的 .NET C# 程序中对其进行测试并使用诸如 socket.send() 和 socket.receive() 之类的阻塞调用时,它可以工作,但 Windows Phone 应用程序没有阻塞调用。这就是服务器 (Java) 在检测到连接后所做的事情:

BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream(), "UTF-8"));
String message = reader.readLine();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(clientSocket.getOutputStream(), "UTF-8"));
writer.println("hiBack");
writer.close();

这就是客户端(C#)的实现方式:

public void sendRequest()
{
   socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
   var connectionOperation = new SocketAsyncEventArgs { RemoteEndPoint = new DnsEndPoint(server, serverPort) };
   connectionOperation.Completed += new EventHandler<SocketAsyncEventArgs>(onConnectCompleted);
   socket.ConnectAsync(connectionOperation);
 }

 private void onConnectCompleted(object sender, SocketAsyncEventArgs e)
 {
    if (e.SocketError != SocketError.Success)
    {
       System.Console.WriteLine("Error! " + e.SocketError);
       return;
     }
     var sendListener = new SocketAsyncEventArgs();
     string msg = "hi";
     var buffer = new System.Text.UTF8Encoding().GetBytes(msg + Environment.NewLine);
     sendListener.SetBuffer(buffer, 0, buffer.Length);
     sendListener = new SocketAsyncEventArgs { RemoteEndPoint = new DnsEndPoint(server, serverPort) };
     sendListener.Completed += new EventHandler<SocketAsyncEventArgs>(onSendCompleted);
     socket.SendToAsync(sendListener);
 }

 private void onSendCompleted(object sender, SocketAsyncEventArgs e)
 {
      socket.ReceiveAsync(e);
 }

我的线路有问题:socket.SendToAsync(sendListener); 在 C# 端结束程序而不做任何事情(返回代码 0 退出)。Java服务器在检测到连接时立即启动它的工作,所以它也可能导致问题?我可以做些什么来使沟通工作?

4

0 回答 0