描述:一个客户端,可以发送多条信息给服务端,只是在单发案例中加上了死循环,可以不断输入消息。
服务端:
服务端的代码和单发无异,具体代码注释可看单发案例
public class Server {
public static void main(String[] args) throws Exception{
System.out.println("服务端启动.......");
ServerSocket serverSocket = new ServerSocket(8888);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null){
System.out.println("服务端收到消息:"+line);
}
}
}
客户端:
public class Client {
public static void main(String[] args) throws Exception{
System.out.println("客户端启动.......");
Socket socket = new Socket("127.0.0.1",8888);
OutputStream outputStream = socket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
Scanner scanner = new Scanner(System.in);
while (true){
System.out.print("请输入:");
String msg = scanner.nextLine();
printStream.println(msg);
printStream.flush();
}
}
}