所以这是我尝试“设置”的第一个服务器客户端,但它无法按我想要的方式工作。这是我想要的:
客户端要做的事情:(请参阅客户端代码中的注释)
- “用户输入”应由客户端读取
- 将“用户输入”发送到服务器
- 从服务器接收一些东西
服务器要做的事情:(参见服务器代码中的注释)
- 接收客户端读取的“用户输入”
- 利用“用户输入”执行某些操作
- 将 (2) 中完成的操作发送回客户端。
它不起作用,它正在做的唯一正确的事情是它接收来自“用户”的输入,就是这样:
public class Cli {
BufferedReader in;
PrintWriter out;
Socket s;
public Cli(int port){
try {
s = new Socket("127.0.0.1", port);
out = new PrintWriter(s.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader
(s.getInputStream()));
} catch (UnknownHostException e) {
System.out.print("fel");
} catch (IOException e) {
System.out.print("fel");
}
}
public void startaClient(){
BufferedReader stdIn = new BufferedReader (new InputStreamReader(System.in));
try {
while(true){
String userInput = stdIn.readLine();// get the user input (1)
System.out.print("from user: " + userInput);
out.write(userInput); // sends to server (2)
System.out.println(in.readLine()); // receive from server(3)
}
} catch (Exception e){
System.out.println("fel1");
}
}
public static void main(String[] args){
Cli c=new Cli(4002);
c.startaClient();
}
这是服务器的代码:
public class Ser {
ServerSocket s;
public Ser()throws Exception{
s = new ServerSocket(4002);
}
public void startaServern()throws Exception {
while (true) {
Socket socket = s.accept(); //waits for new clients, acceptera inkommande förfrågan
Trad t = new Trad(socket);
t.start();
}
}
public static void main(String[] args)throws Exception{
Ser b = new Ser();
b.startaServern();
}
}
public class Trad extends Thread {
Socket socket;
BufferedReader in;
PrintWriter out;
public Trad(Socket s){
socket=s;
try{
in = new BufferedReader(new InputStreamReader(socket.getInputStream())); //
out=new PrintWriter(socket.getOutputStream(),true);
}catch(Exception e){System.out.println("fel");}
}
public void run(){
while(true){
try{
String theInput = in.readLine(); //read, receive message from client (1)
String res = theInput+"blabla"; // do something with the message from the client (2)
out.write(res); // send it back to the client (3)
} catch(Exception e) {
System.out.println("fel1");
}
}
}
}
最佳答案
当您执行readLine()
时,它将读取一行,即直到到达新行。
除非您发送新行,否则它将永远等待。我建议您发送一个换行符,以便读者知道该行已经结束。
由于您使用的是PrintWriter
,最简单的解决方案是使用
out.println(res);
而不是out.write(res);
关于java - 服务器-客户端这里出了什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35973941/