java socket编程

server端:

 1 import java.io.BufferedReader;
 2 import java.io.IOException;
 3 import java.io.InputStream;
 4 import java.io.InputStreamReader;
 5 import java.io.OutputStream;
 6 import java.net.ServerSocket;
 7 import java.net.Socket;
 8 
 9 
10 public class ServerSocketTest {
11 
12     
13     public static void main(String[] args) {
14         try {
15             ServerSocket ss=new ServerSocket(1235);
16             System.out.print("server");
17             Socket socket=ss.accept();
18             
19             InputStream is=socket.getInputStream();
20             BufferedReader br = new BufferedReader(new InputStreamReader(is));
21             String info=null;
22             if((info=br.readLine())!=null){
23                 System.out.print(info);
24             }
25             
26             OutputStream os=socket.getOutputStream();
27             String s="hello";
28             os.write(s.getBytes());
29             
30             os.close();
31             br.close();
32             is.close();
33             socket.close();
34             ss.close();
35             
36         } catch (IOException e) {
37             e.printStackTrace();
38         }
39 
40     }
41 
42 }

client端:

 1 import java.io.BufferedReader;
 2 import java.io.IOException;
 3 import java.io.InputStream;
 4 import java.io.InputStreamReader;
 5 import java.io.OutputStream;
 6 import java.net.Socket;
 7 import java.net.UnknownHostException;
 8 
 9 
10 public class SocketTest {
11 
12     
13     public static void main(String[] args) {
14         try {
15             Socket socket=new Socket("localhost", 1235);
16             System.out.println("client");
17             OutputStream os=socket.getOutputStream();
18             String s="123";
19             os.write(s.getBytes());
20             socket.shutdownOutput();
21             
22             InputStream is=socket.getInputStream();
23             BufferedReader br = new BufferedReader(new InputStreamReader(is));
24             String info=null;
25             if((info=br.readLine())!=null){
26                 System.out.print(info);
27             }
28             
29             br.close();
30             is.close();
31             os.close();
32             socket.close();
33             
34         } catch (UnknownHostException e) {            
35             e.printStackTrace();
36         } catch (IOException e) {            
37             e.printStackTrace();
38         }
39 
40     }
41 
42 }

 

posted on 2018-05-19 16:25  米虫爱喝咖啡  阅读(88)  评论(0编辑  收藏  举报

导航