socke常也称作"套接字",用于描述IP地址和端口,是一个通信链的句柄。应用通常通过"套接字"向网络发出请求或者应答网络请求。
编写socke的服务器端代码:
package com.evan.blog; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; public class BlogServer { public static void main(String[] args) { try { ServerSocket serverSocket = new ServerSocket(8080); Socket socket = serverSocket.accept(); InputStream is = socket.getInputStream(); byte[] b = new byte[1024]; int len; StringBuffer sb = new StringBuffer(); while ((len = is.read(b)) != -1) { String str = new String(b, 0, len); sb.append(str); } is.close(); System.out.println(sb.toString()); System.out.println("有人访问本机的8080端口了,并传入了‘" + sb.toString() + "‘值"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }客户端源码:
package com.evan.blog; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; public class BlogClient { public static void main(String[] args) { try { Socket socket = new Socket(InetAddress.getLocalHost() .getHostAddress(), 8080);//得到本机的IP地址 OutputStream os = socket.getOutputStream(); String str = "my blog socket"; os.write(str.getBytes()); os.flush(); os.close(); } catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }