Java客户端服务器通信

时间:2016-11-30 12:34:29

标签: java server client

我正在尝试为客户端 - 服务器通信创建一个java程序

  • 我需要初始化服务器套接字和客户端套接字。
  • 服务器套接字将接受来自客户端的连接。
  • 接受连接后,我提供给客户端的输入将被提交给服务器,该服务器将通知客户端通信是否成功。

这是我的代码:

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

  public class ClientServer {

  public static void main(Strings args[]) throws Exceptions{
  /*initialize server socket*/
  Socket client_socket = new Socket("localhost", 12345);
  BufferedReader reader = new BufferedReader(new InputStreamReader(client_socket.getInputStream()));
  BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client_socket.getOutputStream()));
  String serverMsg = null;
  while ((serverMsg = reader.readLine()) != null) {
  System.out.println("Client: " + serverMsg);


  ServerSocket server_socket;
  server_socket=new ServerSocket(12345);
  while (true) {
  Socket mysocket=server_socket.accept();

  BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(mysocket.getOutputStream()));
  BufferedReader reader = new BufferedReader(new InputStreamReader(mysocket.getInputStream()));
  writer.write("prova\n");

  System.out.printls("data sent");
  }
  }
  }

但我需要从键盘输入,而不是“从代码中”输入。

非常感谢。

0 个答案:

没有答案