Android 中的 Socket 仍然卡住

发布于 2024-12-24 02:16:48 字数 3763 浏览 0 评论 0原文

我有一个用 C# 编写的服务器和一个用 Android 编写的客户端。如果我从客户端(Android)向服务器(c#)以及从服务器向客户端发送消息,则一切正常。如果我尝试从客户端发送一条消息,从服务器发送一条消息,从客户端发送另一条消息,则客户端仍停留在从服务器读取消息的状态。可能是什么问题? 我的客户端代码是:

 sendBytes("HELLOX".getBytes());
 readBytes(byDataReceived);//here it gets stucked
...
        try
        {
            int nrsend=sendBytes("HELLOX".getBytes()); 
            readBytes(byDataReceived);
        }
        catch (Exception se)
        {
            Log.d("IdealLog","Exception: "+se.getMessage()+" ");
            Toast.makeText(context, se.getMessage()+" " , 10000).show();
           // MessageBox.Show(se.Message);
            return false; 
        }
...
 public static int readBytes(byte[] myByteArray) throws IOException 
 {
          Log.d("IdealLog","readBytes-begin");
        InputStream in = socket.getInputStream();
        BufferedReader buffreader = new BufferedReader(new InputStreamReader(in)); 
        String finalText = "";
        String text = "";
        while ((text = buffreader.readLine()) != null) 
        {
            finalText += text;
        }  
        myByteArray=new byte[myByteArray.length];
        myByteArray=EncodingUtils.getAsciiBytes(finalText);
        Log.d("IdealLog","Input Stream: "+finalText);
        Log.d("IdealLog","TEST: "+EncodingUtils.getAsciiString(myByteArray));
        Log.d("IdealLog","readBytes-end");

        byDataReceived=myByteArray;
        buffreader.close();
        return myByteArray.length;//myByteArray.length;
 }//readBytes end
  public static int sendBytes(byte[] myByteArray) throws IOException 
    {
        return sendBytes(myByteArray, 0, myByteArray.length);
    }//sendBytes end

    public static int sendBytes(byte[] myByteArray, int start, int len) throws IOException 
    {
        if (len < 0)
        {
            throw new IllegalArgumentException("Negative length not allowed");
        }
        if (start < 0 || start >= myByteArray.length)
        {
            throw new IndexOutOfBoundsException("Out of bounds: " + start);
        }
        OutputStream out = socket.getOutputStream(); 
        DataOutputStream dos = new DataOutputStream(out);
       // dos.writeInt(len);
        if (len > 0) 
        {
            dos.write(myByteArray, start, len);
        }
        int size=dos.size();
        dos.flush();
       return size;
    }//sendBytes end

我的服务器代码:

static void Main(string[] args)
    {
        IPEndPoint ip = new IPEndPoint(IPAddress.Any, 1408);
        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        socket.Bind(ip);
        socket.Listen(10);
        Console.WriteLine("Waiting for a client...");
        Socket client = socket.Accept();
        IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
        Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port);



        string welcome = "HELLO&";
        byte[] data = new byte[200];
        client.Receive(data);
        Console.WriteLine("Received data from CLIENT TEST1: {0}", System.Text.ASCIIEncoding.ASCII.GetString(data));

        ASCIIEncoding asen = new ASCIIEncoding();
        byte[] data2 = new byte[200];
        data2 = asen.GetBytes(welcome);
        client.Send(data2, data2.Length, SocketFlags.None);



 //if i comment out from this 3 lines, everything is working fine
        byte[] data3 = new byte[200];//this
        client.Receive(data3);//this
        Console.WriteLine("Received data from CLIENT TEST2: {0}", System.Text.ASCIIEncoding.ASCII.GetString(data3));//this



        Console.WriteLine("Disconnected from {0}", clientep.Address);
        client.Close();
        socket.Close();

        Console.ReadLine();
    }

I have a server written in C# and a client side in Android. If I send a message from client (Android) to server (c#) and from server to client, everything works fine. If I try to send one message from client , one from server, another from client, the client remains stuck at reading the message from the server. What could be the problem?
My client code is:

 sendBytes("HELLOX".getBytes());
 readBytes(byDataReceived);//here it gets stucked
...
        try
        {
            int nrsend=sendBytes("HELLOX".getBytes()); 
            readBytes(byDataReceived);
        }
        catch (Exception se)
        {
            Log.d("IdealLog","Exception: "+se.getMessage()+" ");
            Toast.makeText(context, se.getMessage()+" " , 10000).show();
           // MessageBox.Show(se.Message);
            return false; 
        }
...
 public static int readBytes(byte[] myByteArray) throws IOException 
 {
          Log.d("IdealLog","readBytes-begin");
        InputStream in = socket.getInputStream();
        BufferedReader buffreader = new BufferedReader(new InputStreamReader(in)); 
        String finalText = "";
        String text = "";
        while ((text = buffreader.readLine()) != null) 
        {
            finalText += text;
        }  
        myByteArray=new byte[myByteArray.length];
        myByteArray=EncodingUtils.getAsciiBytes(finalText);
        Log.d("IdealLog","Input Stream: "+finalText);
        Log.d("IdealLog","TEST: "+EncodingUtils.getAsciiString(myByteArray));
        Log.d("IdealLog","readBytes-end");

        byDataReceived=myByteArray;
        buffreader.close();
        return myByteArray.length;//myByteArray.length;
 }//readBytes end
  public static int sendBytes(byte[] myByteArray) throws IOException 
    {
        return sendBytes(myByteArray, 0, myByteArray.length);
    }//sendBytes end

    public static int sendBytes(byte[] myByteArray, int start, int len) throws IOException 
    {
        if (len < 0)
        {
            throw new IllegalArgumentException("Negative length not allowed");
        }
        if (start < 0 || start >= myByteArray.length)
        {
            throw new IndexOutOfBoundsException("Out of bounds: " + start);
        }
        OutputStream out = socket.getOutputStream(); 
        DataOutputStream dos = new DataOutputStream(out);
       // dos.writeInt(len);
        if (len > 0) 
        {
            dos.write(myByteArray, start, len);
        }
        int size=dos.size();
        dos.flush();
       return size;
    }//sendBytes end

My server code:

static void Main(string[] args)
    {
        IPEndPoint ip = new IPEndPoint(IPAddress.Any, 1408);
        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        socket.Bind(ip);
        socket.Listen(10);
        Console.WriteLine("Waiting for a client...");
        Socket client = socket.Accept();
        IPEndPoint clientep = (IPEndPoint)client.RemoteEndPoint;
        Console.WriteLine("Connected with {0} at port {1}", clientep.Address, clientep.Port);



        string welcome = "HELLO&";
        byte[] data = new byte[200];
        client.Receive(data);
        Console.WriteLine("Received data from CLIENT TEST1: {0}", System.Text.ASCIIEncoding.ASCII.GetString(data));

        ASCIIEncoding asen = new ASCIIEncoding();
        byte[] data2 = new byte[200];
        data2 = asen.GetBytes(welcome);
        client.Send(data2, data2.Length, SocketFlags.None);



 //if i comment out from this 3 lines, everything is working fine
        byte[] data3 = new byte[200];//this
        client.Receive(data3);//this
        Console.WriteLine("Received data from CLIENT TEST2: {0}", System.Text.ASCIIEncoding.ASCII.GetString(data3));//this



        Console.WriteLine("Disconnected from {0}", clientep.Address);
        client.Close();
        socket.Close();

        Console.ReadLine();
    }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

请叫√我孤独 2024-12-31 02:16:48

修改成这样:

   //if i comment out from this 3 lines, everything is working fine
   byte[] data3 = new byte[200];//this 
   client.Receive(data3);//this    
   Console.WriteLine("Received data from CLIENT TEST2: {0}", System.Text.ASCIIEncoding.ASCII.GetString(data3));//this 

   client.Send(data2, data2.Length, SocketFlags.None); 

   Console.WriteLine("Disconnected from {0}", clientep.Address); 
   client.Close();       
   socket.Close();       
   Console.ReadLine(); 
}

Modify into this:

   //if i comment out from this 3 lines, everything is working fine
   byte[] data3 = new byte[200];//this 
   client.Receive(data3);//this    
   Console.WriteLine("Received data from CLIENT TEST2: {0}", System.Text.ASCIIEncoding.ASCII.GetString(data3));//this 

   client.Send(data2, data2.Length, SocketFlags.None); 

   Console.WriteLine("Disconnected from {0}", clientep.Address); 
   client.Close();       
   socket.Close();       
   Console.ReadLine(); 
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文