客户端Socket:
public class ClientSocket { public static void testClientSocket() throws Exception { try { Socket socket = new Socket("localhost", 8888); // setSoTimeOut:设置客户端Socket读取数据的超时时长。 socket.setSoTimeout(3000); // setKeepAlive:该方法指定检测与服务器的链接状态。 socket.setKeepAlive(true); // setTcpNoDelay:Nagle算法;优点很明显,节省了通信的开销。 socket.setTcpNoDelay(true); // setSoLinger:其实该方法和Socket的关闭方法( close() )是有联系的。 socket.setSoLinger(true, 5); // setReceiveBufferSize:设置输入流的缓冲大小。默认情况下,输入流的接收缓冲区是8096个字节(8K)。 socket.setReceiveBufferSize(1024); // 如果你的服务程序停止后想立即重启,不等60秒,而新套接字依旧 使用同一端口,此时 SO_REUSEADDR 选项非常有用。 socket.setReuseAddress(true); OutputStream os = socket.getOutputStream(); // 给服务端传值 os.write("你好 I'm client".getBytes()); byte[] readbyte = new byte[40]; InputStream ins = socket.getInputStream(); ins.read(readbyte); // 打印服务端返回值 System.out.println(new String(readbyte)); System.out.println("打印服务端返回值"); } catch(SocketException e){ e.printStackTrace(); }catch (UnknownHostException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { try { testClientSocket(); } catch (Exception e) { e.printStackTrace(); } } }
服务端的serverSocket:
public class TestServerSocket { public static void testServerSocketMethod() throws Exception { ServerSocket serverSocket = null; Socket socket2 = null; try { //1.注册ip和端口,注册了一个服务器程序 serverSocket = new ServerSocket(8888); //2.等待接收连接请求,并且连接成功后创建Socket。 // 收到客户端发送的数据才会继续向下执行。 socket2 = serverSocket.accept(); System.out.println("connect ok"); //3.获得连接对象的网络流,从而进行网络数据传输 // 获得客户端数据 byte[] readbyte = new byte[40]; InputStream ins = socket2.getInputStream(); ins.read(readbyte); System.out.println("打印客户端返回值"); System.out.println(new String(readbyte)); // 往客户端发数据 OutputStream os = socket2.getOutputStream(); os.write("你好 I'm server".getBytes()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void main(String[] args) { try { testServerSocketMethod(); } catch (Exception e) { e.printStackTrace(); } } }