Document

今天写了一个客户端与服务器端的通信

服务器端代码:

 1 package com.mon10.day23;
 2 /** 
 3 * 类说明 :服务器端
 4 * @author 作者 : chenyanlong 
 5 * @version 创建时间:2017年10月23日 
 6 */
 7 import java.io.*;
 8 import java.net.ServerSocket;
 9 import java.net.Socket;
10 public class TestServerSocket {
11 
12     public static void main(String[] args) throws IOException {
13         
14         ServerSocket ss=new ServerSocket(6669);
15         
16         while(true){
17             Socket s=ss.accept();
18             System.out.println("A Client Connected!");
19             
20             /*使用InputStream流接收从客户端发送过来的信息,使用DataInputStream数据流处理接收到的信息*/
21             DataInputStream dis=new DataInputStream(s.getInputStream());
22             
23             String str=dis.readUTF();
24             System.out.println(str);
25         }
26     }
27 }

客户端代码:

 1 /** 
 2 * 类说明 :客户端
 3 * @author 作者 : chenyanlong 
 4 * @version 创建时间:2017年10月23日 
 5 */
 6 package com.mon10.day23;
 7 import java.io.DataOutputStream;
 8 import java.io.IOException;
 9 import java.io.OutputStream;
10 import java.net.Socket;
11 public class TestClientSocket {
12     
13     public static void main(String[] args) throws Exception {
14         
15         //创建一个流套接字并将其连接到指定 IP 地址的指定端口号。
16         Socket s=new Socket(" 192.168.125.118",6669);
17         //10.2.11.39
18        /*Client申请链接到Server端,连接上服务器端以后,就可以向服务器端输出信息和接收从服务器端返回的信息
19            输出信息和接收返回信息都要使用流式的输入输出原理进行信息的处理*/
20                   
21         /*这里是使用输出流OutputStream向服务器端输出信息*/        
22         OutputStream os=s.getOutputStream();
23         DataOutputStream dos=new DataOutputStream(os);
24         
25         Thread.sleep(30000);/*客户端睡眠30秒后再向服务器端发送信息*/
26         int i=1;
27         dos.writeUTF("Hello Server!"+"第"+i+"次发送");
28     }
29 
30 }
原文地址:https://www.cnblogs.com/chenyanlong/p/7719177.html