一、服务端
1 public class SocketServer implements Runnable { 2 3 //端口 4 private final int port; 5 6 private ServerSocket ss; 7 8 /** 9 * 10 */ 11 public SocketServer(int port) { 12 this.port = port; 13 } 14 15 16 public void server(){ 17 // socket(AF_INET,SOCK_STREAM,IPPOTO_TCP); 18 try { 19 // 服务端阻塞接收客户端请求 20 Socket s = ss.accept(); 21 //输入流封装 22 DataInputStream din = new DataInputStream(s.getInputStream()); 23 //数据接受 24 String req = din.readUTF(); 25 System.out.println("服务端请求数据:"+req); 26 //输出流封装 27 DataOutputStream dou = new DataOutputStream(s.getOutputStream()); 28 String s1 = "收到,收到。我是08"; 29 //数据发送 30 dou.writeUTF(s1); 31 //刷出数据 32 dou.flush(); 33 //关闭流和socket 34 dou.close(); 35 din.close(); 36 37 s.close(); 38 } catch (IOException e) { 39 // TODO Auto-generated catch block 40 e.printStackTrace(); 41 } 42 } 43 44 /** 45 * runnable接口 46 */ 47 public void run() { 48 // TODO Auto-generated method stub 49 try { 50 System.out.println("服务端启动 ,开启:"+port+"端口"); 51 ss = new ServerSocket(port); 52 } catch (IOException e) { 53 // TODO Auto-generated catch block 54 e.printStackTrace(); 55 } 56 while(true){ 57 server(); 58 } 59 } 60 61 public static void main(String[] args) { 62 SocketServer ss = new SocketServer(8090); 63 64 Thread th = new Thread(ss); 65 66 th.start(); 67 } 68 }
二、客户端
1 public class SocketClient{ 2 3 /** 4 * 连接服务器 5 */ 6 public void client(){ 7 Socket so = null; 8 try { 9 //根据ip和端口来获取socket对象 10 so = new Socket("192.168.0.114",8090); 11 //根据socket对象来获取输出流 12 // OutputStream out = so.getOutputStream(); 13 //根据socket对象来获取输出流 14 DataOutputStream out = new DataOutputStream(so.getOutputStream()); 15 //获取本地的ip 16 System.out.println(so.getLocalAddress()); 17 //获取本地的端口 18 System.out.println(so.getLocalPort()); 19 //根据socket对象来获取输入流,获取目标对象的返回信息 20 // InputStream out = so.getInputStream(); 21 DataInputStream in = new DataInputStream(so.getInputStream()); 22 //返回信息接D收byte数组 23 byte[] b = new byte[1024]; 24 //定义发送过去的信息 25 // String str = "bye"; 26 //将String类型转换为byte数组,并将编码格式设置为utf-8 27 // byte[] by = str.getBytes("UTF-8"); 28 //通过输出流发送信息 29 // out.write(by); 30 out.writeUTF("我是07,我是07,收到请回复"); 31 //将信息刷过去 32 out.flush(); 33 //通过输入流获取返回的信息并存储到byte数组b中 34 // in.read(b); 35 //直接读取utf格式 36 String resp=in.readUTF(); 37 //打印接受的信息,并将byte数组转换为String类型,并将编码格式转换为utf-8 38 // System.out.println(new String(b,"utf-8")); 39 System.out.println(resp); 40 //关闭输入流、输出流和socket 41 in.close(); 42 out.close(); 43 so.close(); 44 } catch (UnknownHostException e) { 45 // TODO Auto-generated catch block 46 e.printStackTrace(); 47 } catch (IOException e) { 48 // TODO Auto-generated catch block 49 e.printStackTrace(); 50 } 51 } 52 53 54 public static void main(String[] args) { 55 SocketClient sc = new SocketClient(); 56 sc.client(); 57 } 58 59 }