zoukankan      html  css  js  c++  java
  • Socket结合Thread简单实例

    (1)Server类

     1 public class Server {
     2     public static void main(String[] args) {
     3         ServerSocket server = null;
     4         try {
     5             server = new ServerSocket(9000);
     6             while(true) {
     7                 Socket socket = server.accept();
     8                 MyThread myThread = new MyThread(socket);
     9                 myThread.start();
    10             }
    11         } catch (IOException e) {
    12             e.printStackTrace();
    13         }
    14     }
    15 }

    (2)MyThread类

     1 public class MyThread extends Thread {
     2     private Socket socket;
     3     public MyThread(Socket socket) {
     4         this.socket = socket;
     5     }
     6     @Override
     7     public void run() {
     8         InputStream is = null;
     9         try {
    10             is = socket.getInputStream();
    11             InputStreamReader isr = new InputStreamReader(is);
    12             BufferedReader br = new BufferedReader(isr);
    13             String message = br.readLine();
    14             System.out.println("客户端发来的消息:"+message);
    15             is.close();
    16         } catch (IOException e) {
    17             e.printStackTrace();
    18         }
    19     }
    20 }

    (3)Client类

     1 public class Client {
     2     public static void main(String[] args) {
     3         Socket socket = null;
     4         try {
     5             socket = new Socket("localhost", 9000);
     6             OutputStream os = socket.getOutputStream();
     7             os.write("hello".getBytes());
     8             os.close();
     9         } catch (IOException e) {
    10             e.printStackTrace();
    11         }
    12     }
    13 }
  • 相关阅读:
    http
    python的列表生成式
    flask的登陆验证
    脚本更新流程
    k8s中job和pod的区别
    k8s中一些常见概念
    supervisord部署和使用
    flask中config
    python类的继承super()的使用
    python中类的继承
  • 原文地址:https://www.cnblogs.com/mituxiaogaoyang/p/8422884.html
Copyright © 2011-2022 走看看