首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android套接字异常“套接字关闭”

Android套接字异常“套接字关闭”
EN

Stack Overflow用户
提问于 2012-01-12 16:58:52
回答 3查看 13.7K关注 0票数 6

当我尝试使用下面的代码运行由echo服务器和android客户端组成的测试时,我总是会得到异常msg“套接字已关闭”。这段代码可以简单地将msg发送到服务器,并从服务器接收msg,但是如果您想同时执行这两种操作,它就是不能工作.我很好奇它为什么会导致这样的问题,如果我希望它能够首先将msg发送到echo服务器,我应该如何解决它?

然后从回波服务器接收消息?

代码语言:javascript
复制
            // 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();
            }

不幸的是,它仍然不能工作,...I按照您的指示修改代码以:

代码语言:javascript
复制
            // 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编写的代码:

代码语言:javascript
复制
# 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()
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-01-12 18:09:57

我想你做得对,顺序不对。可能是服务器太快了,当您试图读取响应时,它已经接收到并消失了。

遵循教程从插座读取和写入套接字中提供的规则

  1. 打开插座
  2. 打开输入流并将流输出到套接字。
  3. 根据服务器协议从流中读取并写入流。
  4. 关闭溪流。
  5. 关闭插座。

你看到区别了吗?首先打开输入和输出流,然后开始发送请求。

我相信如果你坚持这份订单,它一定会成功的。

票数 6
EN

Stack Overflow用户

发布于 2018-04-04 04:22:55

我有一个类似的问题,通过编辑gradle.properties文件来允许代理连接来解决这个问题。我添加了前面的行,就像Nadeem在https://github.com/facebook/react-native/issues/2726上解释的那样

代码语言:javascript
复制
systemProp.http.proxyHost=proxyHost
systemProp.http.proxyPort=proxyPort

systemProp.https.proxyHost=proxyHost
systemProp.https.proxyPort=proxyPort
票数 0
EN

Stack Overflow用户

发布于 2012-01-13 10:13:08

您的应用程序需要AndroidManifest.xml中的互联网许可

代码语言:javascript
复制
<uses-permission android:name="android.permission.INTERNET"/>
票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8839019

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档