这是代码。
public class testClient {
public static void main(String[] args) {
testClient abc = new testClient();
abc.go();
}
public void go() {
try {
Socket s = new Socket("127.0.0.1", 5000);
InputStreamReader sr = new InputStreamReader(s.getInputStream());
BufferedReader reader = new BufferedReader(sr);
String x = reader.readLine();
System.out.println(x);
reader.close();
} catch(IOException ex) {
ex.printStackTrace();
}
}
}
public class testServer {
public static void main(String[] args) {
testServer server = new testServer();
server.go();
}
public void go() {
try {
ServerSocket s = new ServerSocket(5000);
while(true) {
Socket sock = s.accept();
PrintWriter writer = new PrintWriter(sock.getOutputStream());
String toReturn = "No cake for you.";
writer.println(toReturn);
}
} catch(IOException ex) {
ex.printStackTrace();
}
}
}
java.io.*
和java.net.*
都会在这两个类中导入。
现在,当我尝试运行这些(使用不同的终端)时,没有任何反应。我做错了什么?
答案 0 :(得分:5)
您的输出显然是缓冲的。写完输出后,尝试刷新:
writer.println(toReturn);
writer.flush();
此外,如果您已完成套接字,您可以考虑在服务器中调用sock.close()
,否则客户端将不知道下一步该做什么。
答案 1 :(得分:5)
使用PrintWriter时,需要调用flush方法。将您的代码更改为以下内容并且有效:)。
public class testServer {
public static void main(String[] args) {
testServer server = new testServer();
server.go();
}
public void go() {
try {
ServerSocket s = new ServerSocket(5000);
while(true) {
Socket sock = s.accept();
PrintWriter writer = new PrintWriter(sock.getOutputStream());
String toReturn = "No cake for you.";
writer.println(toReturn);
writer.flush();
}
} catch(IOException ex) {
ex.printStackTrace();
}
}
}
答案 2 :(得分:1)
查看这个简单的工作示例。
import java.net.*;
import java.io.*;
public class Server {
Server() throws IOException {
ServerSocket server = new ServerSocket( 4711 );
while ( true ) {
Socket client = server.accept();
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
int multiplikator1 = in.read();
int multiplikator2 = in.read();
int resultat = multiplikator1 * multiplikator2;
out.write(resultat);
}
public static void main (String[] args) {
try {
Server server = new Server();
} catch (IOException e) {
e.printStackTrace();
}
}
}
import java.net.*;
import java.io.*;
public class Client {
Client() throws IOException {
Socket server = new Socket ( "localhost", 4711 );
InputStream in = server.getInputStream();
OutputStream out = server.getOutputStream();
out.write( 4 );
out.write( 9 );
int result = in.read();
System.out.println( result );
server.close();
}
public static void main (String[] args) {
try {
Client client = new Client();
} catch (IOException e) {
e.printStackTrace();
}
}
}
答案 3 :(得分:1)
关闭作家。