服务端:
import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPServer {
public static void main(String[] args) throws Exception{
ServerSocket ss = new ServerSocket(6666);
while(true){//不停接受,可以接受多个
Socket s = ss.accept();//等待,等不到就阻塞。只能接受一个连接,接受后封装成一个Socket
DataInputStream dis = new DataInputStream(s.getInputStream());//数据输入流接收
System.out.println(dis.readUTF());
dis.close();
s.close();
}
}
}
客户端:
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class TCPClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket("127.0.0.1",6666);//创建一个SOCKET连接
OutputStream os = s.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF("hello server");//发送数据
dos.flush();
dos.close();
s.close();
}
}