码迷,mamicode.com
首页 > 编程语言 > 详细

java socket编程

时间:2018-05-19 18:36:57      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:sys   port   adl   line   catch   buffered   read   code   except   

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 }

 

java socket编程

标签:sys   port   adl   line   catch   buffered   read   code   except   

原文地址:https://www.cnblogs.com/mcahkf/p/9060699.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!