基本服务器和客户端交互 - Java



美好的一天,

下面的代码运行,但服务器仅在我终止字符串后写入字符串,或者客户端仅在我终止正在运行的服务器后接收我发送的字符串。 应该发生的情况是在连接时,客户端向服务器发送一条 hello 消息,服务器读取该消息并将其输出到控制台,然后服务器将消息写回客户端,然后客户端读取消息并将其输出到控制台,然后立即断开连接。

public class Server 
{
public static void main(String[] args) 
{
ServerSocket ss;
try {
ss=new ServerSocket(2018);
Socket s=ss.accept();
System.out.println("connected...");
Handler h =new Handler(s);
Thread t=new Thread(h);
t.start();
}catch(IOException ex)
{
ex.printStackTrace();
}
//client handler.
public Handler(Socket s) 
{
cs=s;
}
@Override
public void run() 
{
try 
{
pw=new PrintWriter(cs.getOutputStream());
sc=new Scanner(cs.getInputStream());
pw.write("SERVER SAYS:Hello");
pw.flush();
System.out.println(sc.nextLine());
}catch(IOException e)
{
e.printStackTrace();
}
//then the client.
public class Client {
public static void main(String[] args) 
{
Socket s;
PrintWriter pw;
Scanner sc;
try {
s=new Socket("localhost",2018);
pw=new PrintWriter(s.getOutputStream());
sc=new Scanner(s.getInputStream());
pw.write("HELLO");
pw.flush();
String msg=sc.nextLine();
System.out.println(msg);
}catch(IOException e)
{
e.printStackTrace();
}

您的客户端调用sc.nextLine(),这将阻止,直到流中有换行符或直到连接关闭。由于服务器从不发送换行符 (n(,因此sc.nextLine()仅在您终止服务器后返回。

pw.write("SERVER SAYS:Hello");更改为pw.write("SERVER SAYS:Hellon");,它将按预期工作。

最新更新