Java学习之网络编程(TCP协议实例)

传输控制协议(TCP,Transmission Control Protocol):字面意思传输那就会有源和目的地,TCP中的源和目的地就是客户端和服务端

两个核心类型

1、Socket:客户端套接字

2、ServerSocket:服务端套接字

一、创建客户端思路

  1、创建tcp客户端socket服务,通过Socket对象
    建议一创建就就明确目的地,要连接主机
  2、如果连接建立成功,说明数据传输通道已建立。
    可以通过getOutputStream()和getInputStream()来获取两个字节流
  3、使用输出流,将数据写出
  4、关闭资源
 1 public class ClientDeo {
 2     public static void main(String[] args) throws UnknownHostException, IOException {
 3     //创建客户端socket服务
 4     Socket socket=new Socket("",10002);
 5     //获取socket流中的输出流
 6     
 7     OutputStream out=socket.getOutputStream();
 8     out.write("tcp演示".getBytes());
 9     
10     socket.close();
11     }
12 }

二、创建服务端思路

  1、创建服务的socket服务,通过ServerSocket对象
  2、服务端必须对我提供一个端口,否则客户端无法连接
  3、获取连接过来的客户端对象
  4、通过客户端对象获取socket流读取客户端发送的数据
  5、关闭资源(关闭客户端和服务端)

 1 public class ServerDemo {
 2     public static void main(String[] args) throws IOException {
 3     //创建服务端对象
 4     ServerSocket ss=new ServerSocket(10002);
 5     //获取连接过来的客户端对象
 6     Socket s=ss.accept();
 7     //通过客户端对象获取输入流,要读取客户端发送的数据
 8     InputStream in=s.getInputStream();
 9     BufferedReader br=new BufferedReader(new InputStreamReader(in));
10     
11     String line=null;
12     while((line=br.readLine())!=null) {
13         System.out.println(s.getInetAddress().getHostAddress()+":"+line);
14     }
15     
16     s.close();
17     ss.close();
18     }
19 }

结果:

 分析:

代码展示:

服务端代码

 1 public class ServerDemo2 {
 2     public static void main(String[] args) throws IOException {
 3     //创建服务端对象
 4     ServerSocket ss=new ServerSocket(10003);
 5     //获取连接过来的客户端对象
 6     Socket s=ss.accept();
 7     
 8     //通过客户端对象获取输入流,要读取客户端发送的数据
 9     InputStream in=s.getInputStream();
10     byte[] buf=new byte[1024];
11     int len = in.read(buf);
12     System.out.println(new String(buf,0,len));
13     OutputStream out=s.getOutputStream();
14     out.write("Response...".getBytes());
15     s.close();
16     ss.close();
17     }
18 
19 }

客户端代码:

 1 public class ClientDemo2 {
 2 
 3     /**
 4      * @param args
 5      * @throws IOException 
 6      * @throws UnknownHostException 
 7      */
 8     public static void main(String[] args) throws UnknownHostException, IOException {
 9     //创建客户端socket服务
10     Socket socket=new Socket("172.28.188.168",10003);
11     //获取socket流中的输出流
12     
13     OutputStream out=socket.getOutputStream();
14     out.write("tcp演示,request...".getBytes());
15     out.flush();
16     InputStream in=socket.getInputStream();
17     byte[] buf=new byte[1024];
18     int len = in.read(buf);
19 
20     String text=new String(buf,0,len);
21     System.out.println(text);
22     socket.close();
23     }
24 
25 }

同时上传图片(使用多线线程)

定义线程任务类(实现Runnable接口的类)

 1 public class UploadTask implements Runnable {
 2 
 3     private Socket s;
 4 
 5     public UploadTask(Socket s) {
 6     this.s = s;
 7     }
 8 
 9     @Override
10     public void run() {
11     int count = 0;
12     String ip = s.getInetAddress().getHostAddress();
13     try {
14         // 读取客户端发送来的数据
15         InputStream in = s.getInputStream();
16 
17         // 将读取到数据存储到一个文件中
18         File dir = new File("pic");
19         if (!dir.exists()) {
20         dir.mkdirs();
21         }
22         File file = new File(dir, ip + ".png");
23 
24         //判断文件是否存在
25         if (file.exists()) {
26         file = new File(dir, ip + "(" + (++count) + ").png");
27         }
28 
29         FileOutputStream fos = new FileOutputStream(file);
30         byte[] buf = new byte[1024];
31         int len = 0;
32         while ((len = in.read(buf)) != -1) {
33         fos.write(buf, 0, len);
34         }
35 
36         OutputStream out = s.getOutputStream();
37         out.write("Upload Finish...".getBytes());
38         fos.close();
39         s.close();
40     } catch (Exception e) {
41         // TODO: handle exception
42     }
43     }
44 }

客户端

 1 public class UploadPicClient {
 2 
 3     /**
 4      * @param args
 5      * @throws IOException 
 6      * @throws UnknownHostException 
 7      */
 8     public static void main(String[] args) throws UnknownHostException, IOException {
 9     // 1、创建客户端socket
10     Socket socket = new Socket("172.28.188.168", 10005);
11     // 2、读取客户端要上传的图片文件
12     FileInputStream fis=new FileInputStream("0.png");
13     // 3、获取socket输出流,将图片数据发送给服务器
14     OutputStream out=socket.getOutputStream();
15     // 4、循环写入数据到socket输出流
16     byte[] buf=new byte[1024];
17     int len = 0;
18     while((len=fis.read(buf))!=-1) {
19         out.write(buf,0,len);
20     }
21     // 5、告诉服务器,数据发送完毕,服务器停止读取
22     socket.shutdownOutput();
23 
24     // 读取服务端返回的内容
25     InputStream in=socket.getInputStream();
26     byte[] bufin=new byte[1024];
27     int lenin=in.read(bufin);
28     System.out.println(new String(bufin,0,lenin));
29     // 关闭资源
30     fis.close();
31     socket.close();
32     }
33 }

服务端

 1 public class UploadPicServer {
 2 
 3     /**
 4      * @param args
 5      * @throws IOException
 6      * @throws UnknownHostException
 7      */
 8     public static void main(String[] args) throws UnknownHostException, IOException {
 9     // 创建tcp的socket服务端
10     ServerSocket ss = new ServerSocket(10005);
11 
12     while (true) {
13         // 获取客户端
14         Socket s = ss.accept();
15         new Thread(new UploadTask(s)).start();
16     }
17 //    ss.close();
18     }
19 
20 }

猜你喜欢

转载自www.cnblogs.com/WarBlog/p/12145100.html