2012-01-12 21 views
5

次のコードでエコーサーバーとAndroidクライアントで構成されたテストを実行しようとすると、常に "ソケットが閉じています"という例外メッセージが表示されます。このコードは単にmsgをサーバーに送信し、サーバーからmsgを受け取ることができますが、同時に両方を実行したい場合は機能しません。なぜこの種の問題につながるのかは非常に不思議です。エコーサーバに最初にメッセージを送信できるようにするにはどうすればいいですかAndroidソケット例外 "ソケットが閉じています"

エコーサーバからmsgを受信して​​いますか?

  // 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(); 
      } 

残念ながら、それはまだ動作しません...私はあなたの命令に続き、にコードを変更します。ヘルパーの便宜のために

  // 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書かれたコードです。 :

# 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() 
+3

でINTERNET権限を必要とするが、ここであなたの記事では「攻撃的」言語を投稿しないようにしてください。ありがとうございました。私はあなたのためにそれを固定した。 – prolink007

答えて

5

間違った順序で正しいことをしていると仮定します。サーバーが速すぎる可能性があります。応答を読み取ろうとしているときには、既に受信されています。チュートリアルReading from and Writing to a Socket

  1. オープンソケット
  2. オープンソケットへの入力ストリームと出力ストリームに提示ルールに従う

  3. サーバのプロトコルに従ってストリームに読み書きを行います。
  4. ストリームを閉じます。
  5. ソケットを閉じます。

違いがわかりますか?最初に入力ストリームと出力ストリームを開き、要求の送信を開始します。

この注文に固執すれば効果があります。

+0

いいえ...それはまだ私のために働いていません...とても奇妙な...それはちょうどトーストショーの空の文字列今度は...奇妙な... – shanwu

+1

@ user1145976答えとしてコードを投稿しないでください。ただあなたの質問を更新してください。 _in.available()_を使用しているコードに関しては、特定の状況下でのみ動作します。したがって、使用しないでください。私が好きなサンプルコードをBufferedReaderと_readLine()_で使用してください。 – Robert

-1

あなたのアプリケーションは、あなたのAndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET"/> 
+0

私は、それは動作しませんでした。 – shanwu

+0

これは 'ソケットクローズ'例外を発生させません。 – EJP

関連する問題