服务器端:
public class ServerTCP { public static void main(String[] args) throws IOException { System.out.println("服务器端启动,等待连接"); ServerSocket ss=new ServerSocket(6666); Socket server=ss.accept(); InputStream is=server.getInputStream(); byte[] b=new byte[1024]; int len=is.read(b); String msg=new String(b,0,len); System.out.println(msg); OutputStream out=server.getOutputStream(); out.write("我很好,谢谢你".getBytes()); out.close(); is.close(); server.close(); } }
客户端:
public class ClientTCP { public static void main(String[] args) throws Exception{ System.out.println("客户端 发送数据"); Socket client=new Socket("localhost",6666); OutputStream os=client.getOutputStream(); os.write("你好吗?TCP我来了".getBytes()); InputStream in=client.getInputStream(); byte[] b=new byte[1024]; int len=in.read(b); System.out.println(new String(b,0,len)); in.close(); os.close(); client.close(); } }