日安,
下面的代码运行,但服务器仅在我终止它之后写入字符串,或者客户端仅在我终止正在运行的服务器后接收我发送的字符串。应该发生的情况是,在连接时,客户端向服务器发送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();
}
https://stackoverflow.com/questions/52563391
复制相似问题