一、TCP
Example:
Server:
import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket; public class JavaNet_SocketSever { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub ServerSocket ss=new ServerSocket(10003); Socket s=ss.accept(); InputStream in=s.getInputStream(); byte[] bt=new byte[1024]; int len=in.read(bt); System.out.println(new String(bt,0,len)); s.close(); ss.close(); } }
Client:
import java.io.IOException; import java.io.OutputStream; import java.net.Socket; public class JavaNet_SocketClient { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // TODO Auto-generated method stub Socket s =new Socket("255.255.255.255", 10003); OutputStream out=s.getOutputStream(); out.write("hello".getBytes()); s.close(); } }
原文:http://www.cnblogs.com/weiwoduhigh/p/3557307.html