例 客户端如何连接服务器
public class TestTCPServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(6666);//要指明服务器的端口号
Socket s = ss.accept();//s指服务器与这一个客户端的Socket连接
System.out.println("A Client Connect!");
}
}
public class TestTCPClient {
public static void main(String[] args) throws Exception {Socket s = new Socket("127.0.0.1",6666);//指明服务器的IP地址和端口号
}
}
先运行Server,再运行Client。
Server Console
A Client Connect!
服务器程序往往是和客户端程序一起开发的。
客户端现在已经连接上了服务器,那如何通信呢?
使用流!
例 客户端向服务器发送消息
public class TestTCPServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(6666);
Socket s = ss.accept();//不停的处于接收状态
System.out.println("A Client Connect!");
//一个Socket包含了两个管道,一个输入一个输出。
//拿到输入管道,定义为DataInputStream类型
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println(dis.readUTF());
dis.close();
s.close();
}
}
public class TestTCPClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket("127.0.0.1",6666);
//通过getOutputStream()来拿到输出管道,并定义为DataOutputStream类型
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
Thread.sleep(5000);//使当前线程睡5s,以实验readUTF()是否阻塞,是否等待。
dos.writeUTF("Hello Server.");
dos.flush();//刷新输出流
dos.close();
s.close();
}
}
先运行Server,再运行Client。
Server Console
A Client Connect!
Hello Server.
其中,ss.accept()和readUTF()都是阻塞式的,如果没有数据来,就一直死死等着。
并不是读不到东西就往下运行。
但是线程就被堵住了。
例 服务器向客户端发送消息
public class TestTCPServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(6666);
Socket s = ss.accept();
System.out.println("A Client Connect!");
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
//.getInetAddress()可以拿到客户端的IP地址,.getPort()拿到客户端端口号。
dos.writeUTF("Hello," + s.getInetAddress() + " port#" + s.getPort() + ".");
dos.close();
s.close();
}
}
public class TestTCPClient {
public static void main(String[] args) throws Exception {
Socket s = new Socket("127.0.0.1",6666);
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println(dis.readUTF());
dis.close();
s.close();
}
}
Client Console
Hello,/127.0.0.1 port#2094.