如何循环客户端的套接字读取器

时间:2014-02-09 16:27:50

标签: java sockets

这是我简单的客户端 - 服务器应用程序。我的服务器工作正常,它是循环的,每次客户端连接和写入任何内容时它都会读取客户端的输入。但我不知道如何在客户端代码中循环reader ,所以我可以经常在没有手动重新连接的情况下将消息写入服务器。(我试图将代码放入while(true){}循环但是它不起作用。如果我的简单服务器有任何问题,我感谢任何帮助。谢谢!

客户代码:

import java.io.*;
import java.net.Socket;

public class client{

  private Socket client;
  private String text;
  private PrintWriter writer;
  private BufferedReader reader;

public void connectToServer()throws IOException
{

      client=new Socket("localhost",63400);
      reader=new BufferedReader(new InputStreamReader(System.in));
      writer=new PrintWriter(client.getOutputStream(),true);

      text=reader.readLine();
      writer.println(text);
}

public static void main(String args[])throws IOException
{
  client instance=new client();
  instance.connectToServer();
}
}

服务器代码:

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class server{

   private ServerSocket server;
   private Socket client;
   private BufferedReader reader;
   private String text;


public void startServer()throws IOException{
    server=new ServerSocket(63400);

    while(true)
    {
      client=server.accept();
      reader=new BufferedReader(new InputStreamReader(client.getInputStream()));
      text=reader.readLine();
      System.out.println(text);
    }
}

public static void main(String args[])throws IOException{
    server instance=new server();
    instance.startServer();
}
}

0 个答案:

没有答案