本地PC服务器和android模拟器之间的套接字连接
我在使用套接字连接PC(简单的Java服务器)和android模拟器时遇到了麻烦。连接建立后,服务器发送数据,但当我尝试在android上读取它时,它总是读取一个空字符串。下面是我的一些代码部分:本地PC服务器和android模拟器之间的套接字连接
服务器:
serverSocket = new ServerSocket(8888);
socket = serverSocket.accept();
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
output.write("Output string");
socket.close();
客户:
socket = new Socket("10.0.2.2", 8888);
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String s = input.readLine();
Log.i(TAG, s);
socket.close();
我省略了尝试,渔获物和日志清晰。根据日志,连接建立,服务器发送数据,但客户端只接收空字符串。我会很感激任何帮助。
这对我的作品...(此代码仅用于写入和服务器和客户端读取套接字数据)
服务器:
BufferedOutputStream bos = new BufferedOutputStream(connection.
getOutputStream());
/** Instantiate an OutputStreamWriter object with the optional character
* encoding.
*/
OutputStreamWriter osw = new OutputStreamWriter(bos, "US-ASCII");
String process = "Calling the Socket Server on "+ host + " port " + port;
/** Write across the socket connection and flush the buffer */
osw.write(process);
osw.flush();
客户:
/** Instantiate a BufferedInputStream object for reading
/** Instantiate a BufferedInputStream object for reading
* incoming socket streams.
*/
BufferedInputStream bis = new BufferedInputStream(connection.
getInputStream());
/**Instantiate an InputStreamReader with the optional
* character encoding.
*/
InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");
/**Read the socket's InputStream and append to a StringBuffer */
int c;
while ((c = isr.read()) != 13)
instr.append((char) c);
/** Close the socket connection. */
connection.close();
System.out.println(instr);
}
catch (IOException f) {
System.out.println("IOException: " + f);
}
catch (Exception g) {
System.out.println("Exception: " + g);
}
希望这能帮到你..
我发现了这个问题:我忘了使用output.flush(); – 2011-12-16 12:18:23
模拟器监听他自己的“本地”网络端口。 您应该从本地PC向仿真器端口呼叫端口。
阅读android adb端口转发。
这并没有帮助我。连接建立并且端口被客户端接受 - 但仍然客户端无法通过此套接字接收数据发送 - 服务器发送一些字符串,但客户端只接收空字符串。 – 2011-12-16 11:52:08
喜@yuriy没有什么是你的代码错误其实你不写全行输出流,以它给错误使用它,它为我工作
serverSocket = new ServerSocket(8888);
socket = serverSocket.accept();
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
output.println("Output string");
socket.close();
只是output.println取代output.write在服务器
“连接被拒绝”错误发生。 – 2011-12-16 11:37:18