客户端:
1 package WebProgramingDemo; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.io.OutputStream; 6 import java.net.Socket; 7 import java.net.UnknownHostException; 8 9 public class SocketDemo { 10 11 /** 12 * @param args 13 * @throws IOException 14 * @throws UnknownHostException 15 */ 16 public static void main(String[] args) throws IOException { 17 18 Socket s=new Socket("192.168.2.103",10002); 19 OutputStream out=s.getOutputStream(); 20 out.write("Java".getBytes()); 21 InputStream is=s.getInputStream(); 22 byte buf[]=new byte[1024]; 23 int len=is.read(buf); 24 System.out.println(new String(buf,0,len)); 25 s.close(); 26 } 27 28 }
服务端:
1 package WebProgramingDemo; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.io.OutputStream; 6 import java.net.ServerSocket; 7 import java.net.Socket; 8 9 public class ServerSocketDemo { 10 11 /** 12 * @param args 13 * @throws IOException 14 */ 15 public static void main(String[] args) throws IOException { 16 17 ServerSocket ss = new ServerSocket(10002); 18 Socket s = ss.accept(); 19 String ip = s.getInetAddress().getHostAddress(); 20 System.out.println(ip + "....connected...."); 21 InputStream in = s.getInputStream(); 22 int len = 0; 23 byte[] buf = new byte[1024]; 24 len = in.read(buf); 25 System.out.println(new String(buf, 0, len)); 26 OutputStream os=s.getOutputStream(); 27 os.write("收到".getBytes()); 28 os.close(); 29 s.close(); 30 ss.close(); 31 } 32 33 }