为什么没有任何内容打印到控制台?
我有一个服务器套接字,为每个客户端启动一个新线程。它从客户端读取一行输出并发送自己的响应。这是在客户端打印的。这是代码:
客户端代码:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
PrintWriter out = null;
BufferedReader in = null;
Socket echoSocket=null;
try {
echoSocket = new Socket("localhost", 8999);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
for(int i=0;i<20;i++) {
out.print("Sending to Server"+i);
System.out.println("Received from Server"+in.readLine());
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
try {
in.close();
} finally {
try {
out.close();
} finally {
echoSocket.close();
}
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
服务器代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Server {
/**
* @param args
*/
public static void main(String[] args) {
try {
final ServerSocket server = new ServerSocket(8999);
final ExecutorService threadPool = Executors.newFixedThreadPool(2);
while (true) {
try {
final Socket sock = server.accept();
threadPool.submit(new Callable<Void>() {
@Override
public Void call() throws Exception {
BufferedReader br = null;
PrintWriter out = null;
try {
br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
out = new PrintWriter(sock.getOutputStream(), true);
for (int i = 0; i < 20; i++) {
String readLine = br.readLine();
System.out.println(readLine);
out.print(readLine + "response");
}
} finally {
try {
br.close();
} finally {
try {
out.close();
} finally {
sock.close();
}
}
}
return null;
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
对于一个人来说,你的作者(在客户端和服务器上)应该println
而不是print
。