如题,我写了段Socket服务器\客户端通讯的程序,服务端能接收到客户端的数据,但是客户端就无法接收到服务端传回的数据,代码如下
Server端
[code="java"]
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
-
@author Think
*
*/
public class SocketServer {/**
- @param args */ public static void main(String[] args) { new SocketServer().start(); }
public void start(){
try {
ServerSocket server = new ServerSocket(10086);
while(true){
System.out.println("Waiting for a client...");
Socket client = server.accept();
new SocketServerThread(client).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}class SocketServerThread extends Thread{
Socket client = null;
public SocketServerThread(Socket client){
this.client = client;
}
@Override
public void run(){
try {
// 得到CLIENT的输入流,从输入流出取出传输的数据
BufferedReader reader_from_client = new BufferedReader(new InputStreamReader(client.getInputStream()));
String line = null;
System.out.print("from client message:");
while((line = reader_from_client.readLine()) != null){
System.out.println(line);
}
// 得到CLIENT端的输入流,通过向CLIENT传输数据
PrintWriter writer_to_client = new PrintWriter(client.getOutputStream());
writer_to_client.println("Ok");
writer_to_client.flush();reader_from_client.close(); writer_to_client.close(); client.close(); } catch (IOException e) { } }
}
}
[/code]
Client
[code="java"]import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
/**
-
@author Think
*
*/
public class SocketClient {/**
-
@param args
*/
public static void main(String[] args) {
try {
Socket remoteServer = new Socket(InetAddress.getLocalHost(), 10086);
// 得到SERVER端SOCKET的输出流,通过向输出流写入数据,与SERVER进行通信
PrintWriter write_to_server = new PrintWriter(remoteServer.getOutputStream(), true);
write_to_server.write("Hello, what's you name?");
write_to_server.flush();// 把下面这几行放开,SERVER端就收不到数据了,一直处于阻塞状态 // 得到SERVER端的输出流,从输出流中读取从SERVER传递来的数据
// BufferedReader reader_from_server = new BufferedReader(new InputStreamReader(remoteServer.getInputStream()));
// String line = null;
// while((line = reader_from_server.readLine()) != null){
// System.out.println(line);
// }
// reader_from_server.close();write_to_server.close(); remoteServer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}[/code]
-
如果Client中的说明,只要是Client中放开了
[code="java"]
BufferedReader reader_from_server = new BufferedReader(new InputStreamReader(remoteServer.getInputStream()));
String line = null;
while((line = reader_from_server.readLine()) != null){
System.out.println(line);
}
reader_from_server.close();
[/code]
这段代码,SERVER就阻塞在
[code="java"]
while((line = reader_from_client.readLine()) != null){
[/code]
这行,不知道是哪个环节理解或处理错了,还望大家指点指点!