Socket結合Thread簡單實例

(1)Server類socket

 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類ide

 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類this

 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 }
相關文章
相關標籤/搜索