利用Socket和ServerSocket模拟用户-服务器通讯

客户端:

       public class ClientSocketTest {

 public static void main(String[] args) {
  try {
   //本地计算机模拟:模拟端口8888
   Socket clientSocket = new Socket("localhost", 8888);
   //得到服务器输入流
   InputStream inData = clientSocket.getInputStream();
   //建立输出流至服务器
   OutputStream outData = clientSocket.getOutputStream();
   //发送输出流
   PrintWriter toServer = new PrintWriter(outData, true);
   //键盘输入扫描
   Scanner scanner = new Scanner(System.in);
   //服务器输入扫描
   Scanner data = new Scanner(inData);
   //得到服务器第一行输入信息
   String heading = data.nextLine();
   //打印信息
   System.out.println(heading);
   //键盘输入循环
   while(scanner.hasNextLine()){
    //得到键盘输入信息
    String line = scanner.nextLine();
    //传送至服务器
    toServer.println(line);
    //得到服务器回答信息
    String fromServer = data.nextLine();
    //打印信息
    System.out.println(fromServer);
    if(fromServer.equals("Bye!")){
     System.out.println("Now is disconnection...");
     break;
    }
   }
   clientSocket.close();
  } catch (UnknownHostException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }

 }

}

服务端:

          public class ServerSocketTest {

 public static void main(String[] args) {
  System.out.println("Welcome the server is running...");
  try {
   //服务器监听端口
   ServerSocket serverSocket = new ServerSocket(8888);
   //接受客户端连接
   Socket fromClient = serverSocket.accept();
   System.out.println("Connection to the client...");
   //得到客户端输入流
   InputStream inData = fromClient.getInputStream();
   //得到客户端输出流
   OutputStream outData = fromClient.getOutputStream();
   //创建输出流
   PrintWriter toClient = new PrintWriter(outData, true);
   toClient.println("Type quit to STOP");
   //客户端输入扫描
   Scanner sc = new Scanner(inData);
   //
   while(sc.hasNextLine()){
    //得到客户端输入信息
    String line = sc.nextLine();
    if(line.equalsIgnoreCase("quit")){
     serverSocket.close();
     toClient.println("Bye!");
     break;
    }
    toClient.println(line.toUpperCase());
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值