我遇到了PC (Java编写的简单服务器)和android模拟器的套接字连接问题。连接建立,服务器发送数据,但当我尝试在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();
为了清楚起见,我省略了try-catch和日志。根据日志,连接建立,服务器发送数据,但客户端只接收到空字符串。
这对我有用…(此代码仅用于服务器和客户端从套接字写入和读取数据)
服务器:
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);
}
嗨@yuriy你的代码没有问题,实际上你没有写整行输出流,所以它给出错误使用它它为我工作
serverSocket = new ServerSocket(8888);
socket = serverSocket.accept();
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
output.println("Output string");
socket.close();
只是替换输出。写入并输出。
模拟器监听他"自己的"本地网络端口。您应该从本地pc呼叫端口转发到模拟器端口。
读取android adb端口转发