package test1;import java.io.DataInputStream;import java.net.ServerSocket;import java.net.Socket;public class TcpServer { public static void main(String[] args) throws Exception{ //server在哪个端口上监听客户端的连接 ServerSocket ssServerSocket=new ServerSocket(6666); //接受 while (true){ Socket s=ssServerSocket.accept(); DataInputStream dis=new DataInputStream(s.getInputStream()); System.out.println(dis.readUTF()); dis.close(); s.close(); System.out.println("A client connect!"); } }}
package test1;import java.io.DataOutputStream;import java.io.OutputStream;import java.net.Socket;public class TcpClient { public static void main(String[] args) throws Exception{ //申请和服务器端链接 Socket socket=new Socket("127.0.0.1",6666); //管道发送信息 OutputStream osOutputStream=socket.getOutputStream(); DataOutputStream doStream=new DataOutputStream(osOutputStream); doStream.writeUTF("hello"); doStream.flush(); doStream.close(); socket.close(); }}