【问题标题】:Socket issue c# client to java server套接字问题 c# 客户端到 java 服务器
【发布时间】:2014-10-20 14:23:43
【问题描述】:

这是我的问题,从 c# 客户端发送的所有消息都没有被服务器接收到,直到我关闭客户端的套接字,最后服务器一次接收所有数据。

c#客户端

public static class AsynchronousClient
{
    // The port number for the remote device.
    private const int port = 8888;

    // ManualResetEvent instances signal completion.
    private static ManualResetEvent connectDone =
        new ManualResetEvent(false);
    private static ManualResetEvent sendDone =
        new ManualResetEvent(false);
    private static ManualResetEvent receiveDone =
        new ManualResetEvent(false);

    public static Socket client;
    // The response from the remote device.
    private static String response = String.Empty;

    public static void StartClient()
    {
        // Connect to a remote device.
        try
        {
            // Establish the remote endpoint for the socket.
            // The name of the 
            // remote device is "host.contoso.com".
            IPHostEntry ipHostInfo = Dns.GetHostEntry("127.0.0.1");
            IPAddress ipAddress = ipHostInfo.AddressList[0];
            IPEndPoint remoteEP = new IPEndPoint(ipAddress, 8888);

            // Create a TCP/IP socket.
            client = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);

            // Connect to the remote endpoint.
            client.BeginConnect(remoteEP,
                new AsyncCallback(ConnectCallback), client);
            connectDone.WaitOne();

            // Send test data to the remote device.
            Send(client, "test connection");    
            sentDown.WaitOne();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    public static void ConnectCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the socket from the state object.
            Socket client = (Socket)ar.AsyncState;

            // Complete the connection.
            client.EndConnect(ar);

            Console.WriteLine("Socket connected to {0}",
                client.RemoteEndPoint.ToString());

            // Signal that the connection has been made.
            connectDone.Set();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    public static void Send(Socket client, String data)
    {
        // Convert the string data to byte data using ASCII encoding.
        byte[] byteData = Encoding.ASCII.GetBytes(data);

        // Begin sending the data to the remote device.
        client.BeginSend(byteData, 0, byteData.Length, SocketFlags.None,
            new AsyncCallback(SendCallback), null);
    }

    public static void SendCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the socket from the state object.

            // Complete sending the data to the remote device.
            int bytesSent = client.EndSend(ar);
            Console.WriteLine("Sent {0} bytes to server.", bytesSent);

            // Signal that all bytes have been sent.
            sendDone.Set();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

Java 服务器端

public class Connection_to_port extends Thread {

  final static int port = 8888;
  private Socket socket;
  String message = "";
  public static void main(String[] args) {
    try {
      ServerSocket socketServeur = new ServerSocket(port);
      while (true) {
        Socket socketClient = socketServeur.accept();
        Connection_to_port t = new Connection_to_port(socketClient);
        t.start();
        System.out.println("Connected to client : " + socketClient.getInetAddress());
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public Connection_to_port(Socket socket) {
    this.socket = socket;
  }

  public void run() {
    handleMessage();
  }

  public void handleMessage() {
    try {
      BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      message = in.readLine();
      System.out.println(message);
   }
    catch (Exception e) {
      e.printStackTrace();
    }
}

在我的客户端中,我必须像这样向服务器发送一些数据

AsynchronousClient.Send(AsynchronousClient.client, "{myjsondata}");           

我的客户只是发送,而不是接收。

问题是,我的 java 服务器什么也没收到!但是客户说它已发送,我在 Wireshark 上看到它已发送。

当我这样做时
AsynchronousClient.client.Shutdown(SocketShutdown.Both);

最后我在服务器上同时看到了我的所有消息。就像我只发送一条消息一样。

【问题讨论】:

    标签: java c# sockets


    【解决方案1】:

    Java 端正在尝试读取一行(您正在使用readLine)。

    在出现行尾字符或流关闭之前,此方法不会返回。

    当您关闭客户端时,流实际上会关闭。

    您的测试消息不包含行尾字符,因此readLine 返回的唯一方法是在流的末尾。

    【讨论】:

    • 感谢它的工作,所以添加 \n 是更好的方式,或者可能比 readLine 更好的方式来处理来自客户端的消息?
    • 如果您的消息是纯文本,行尾是一个不错的选择。如果消息需要是其他内容,您还有其他选择。对于 N 个字节的固定长度记录,从流中读取 N 个字节。这完全取决于您要发送的内容。
    【解决方案2】:

    当您写入套接字时,消息不会发送,它会保存在缓冲区中,直到:

    • 缓冲区已满
    • 您请求清理/刷新缓冲区
    • 你关机了。

    尝试以下方法:

    【讨论】:

    • 这并不能解决我的问题,但这是一个有趣的答案 +1。
    猜你喜欢
    • 2011-09-21
    • 1970-01-01
    • 2012-06-24
    • 2014-04-05
    • 2016-12-21
    • 1970-01-01
    • 2012-06-05
    • 2017-05-26
    相关资源
    最近更新 更多