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 }

 

posted @ 2018-02-06 16:16  迷途_小羔羊  阅读(1144)  评论(0编辑  收藏  举报