本文介绍了Android套接字异常“套接字被关闭”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试使用以下代码运行一个包含回声服务器和android客户端的测试时,我总是得到异常msg套接字被关闭。这个代码可以简单地将msg发送到服务器,并从服务器接收msg,但是如果你想同时进行这两个操作,那就不行了...我很好奇为什么会导致这种问题,如果我希望它可以先发送msg到echo server

When I try to run a test composed of an echo server and an android client with the following code, I always get the exception msg "socket is closed". This code can simply send msg to server, and receive msg from server, but if you want to do both at the same time, it just doesn't work... I am very curious why it will lead to this kind of problem, and how should I fix it if I want it to be able to first send msg to echo server

,然后从echo服务器收到msg,那么该怎么解决?

and then receive msg from echo server?

            // Server IP address
            InetAddress serverIp;

            // try to connect Server
            try {

                // set up server IP address
                serverIp = InetAddress.getByName("192.168.17.1");

                // set up port
                int serverPort=12345;

                // initiate socket connection
                Socket clientSocket=new Socket(serverIp,serverPort);

                BufferedOutputStream out = new BufferedOutputStream(clientSocket.getOutputStream());
                out.write("Send From Android1111, stitch ".getBytes());
                out.flush();

                //wait to receive Server's msg
                BufferedReader  br =new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

                total.toString();*/
            // Display received msg with Toast
                Toast.makeText(getApplicationContext(), br.readLine(), Toast.LENGTH_SHORT ).show();

            //close connection
                clientSocket.close();

//              out.close();
//              out = null;
            } catch (IOException e) {
                // display exception with Toast
                Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show();
            }






不幸的是,没有工作...我按照你的说明修改代码:


unfortunately, it still doesn't work ...I followed your instruction and modify the code to:

            // set up Server IP address
            serverIp = InetAddress.getByName("192.168.2.2");

            // set up Server port
            int serverPort=12345;

            // initiate socket connection
            Socket clientSocket=new Socket(serverIp,serverPort);

                // open input and output stream
            OutputStream out = clientSocket.getOutputStream();
            InputStream in = clientSocket.getInputStream();

            //send msg
            out.write("Send From Android1111, bitch ".getBytes());


                // receive msg from server
            byte[] buffer = new byte[in.available()];
            in.read(buffer);
            String rMsg = new String(buffer);
            Toast.makeText(getApplicationContext(), rMsg, Toast.LENGTH_LONG ).show();

            //close input and output stream
            in.close();
            out.close();

             //關閉連線
       clientSocket.close();
        } catch (IOException e) {
            // 出錯後顯示錯誤訊息Toast
            Toast.makeText(getApplicationContext(),e.toString(), Toast.LENGTH_SHORT).show();
        }

为帮助者方便,这里是python编写的服务器部分代码:

for helper's convenience, here's the python written code for server part:

# Practice Echo Server Program written in Python
import socket

# host = '' means it binds to any available interface
host = ''
port = 12345

# socket() function returns a socket object whose methods implement the various socket system calls.
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)

# Bind the socket to address.
s.bind((host,port))

# Listen for connections made to the socket. The backlog argument specifies
# the maximum number of queued connections and should be at least 0;
# the maximum value is system-dependent (usually 5), the minimum value is forced to 0.
s.listen(5)

# Accept a connection. The socket must be bound to an address and listening for
# connections. The return value is a pair (conn, address) where conn is a new socket
# object usable to send and receive data on the connection, and address is the address
# bound to the socket on the other end of the connection.
conn, addr = s.accept()
print 'Connected by', addr

# Receive data from the socket. The return value is a string representing the data received.
# The maximum amount of data to be received at once is specified by bufsize. See the Unix
# manual page recv(2) for the meaning of the optional argument flags; it defaults to zero.
# Note For best match with hardware and network realities, the value of bufsize should be
# a relatively small power of 2, for example, 4096.

while 1:
    data = conn.recv(1024)
    if not data: break
    print 'received data is : ', repr(data)
    conn.send(data)

conn.close()


推荐答案

你正在按正确的顺序做正确的事情。可能是服务器太快,当您尝试阅读已经收到并已经消失的响应时。

I assume you are doing the right things in the wrong order. May be the server is too fast and when you are trying to read the response it is already received and gone.

遵循教程


  1. 打开套接字

  2. 打开一个输入流并输出流到套接字。

  3. 根据服务器协议写入流。

  4. 关闭流。

  5. 关闭套接字。

  1. Open a socket
  2. Open an input stream and output stream to the socket.
  3. Read from and write to the stream according to the server's protocol.
  4. Close the streams.
  5. Close the socket.

你看到不同吗?首先打开输入和输出流,然后开始发送您的请求。

Do you see the difference? First open Input and Output stream and then start sending your request.

我相信如果你坚持这个订单,它将会奏效。

I am sure that if you stick to this order it will work.

这篇关于Android套接字异常“套接字被关闭”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 03:25
查看更多