Java程序设计 网络编程 TCP程序设计
使用Socket(即套接字)完成TCP程序的开发
使用此类可以方便地建立可靠的、双向的、持续的、点对点的通信连接
在Socket的程序开发中,服务器端使用ServerSocket等待客户端的连接,对于Java的网络程序来讲,每一个客户端都使用一个Socket对象表示
ServerSocket类与Socket类
ServerSocket类主要用于服务器端程序的开发,用于接收客户端的连接请求
ServerSocket类
方法 | 作用 |
---|---|
public ServerSocket(int port) throws IOException | 创建ServerSocket实例,并指定监听端口 |
public Socket accept() throws IOException | 等待客户端连接,连接之前一直阻塞 |
public InetAddress getInetAddress() | 返回服务器的IP地址 |
public boolean isClosed() | 返回ServerSocket的关闭状态 |
public void close() throws IOException | 关闭ServerSocket |
在服务器端每次运行时都要使用accept()方法等待客户端连接
此方法执行后服务器端将进入阻塞状态
直到客户端连接后程序才可以向下继续执行
此方法的返回值类型是Socket
每一个Socket都表示一个客户端对象
Socket类
方法 | 作用 |
---|---|
public Socket(String host,int port) throws UnknownHostException,IOException | 构造Socket对象,同时指定要连接服务器的主机名称及连接端口 |
public InputStream getInputStream() throws IOException | 返回此套接字的输入流 |
public OutputStream getOutputStream() throws IOException | 返回此套接字的输出流 |
public void close() throws IOException | 关闭此Socket |
public boolean isClosed() | 判断此套接字是否被关闭 |
在客户端,程序可以通过Socket类的getInputStream()方法取得服务器的输出信息,在服务器端可以通过getOutputStream()方法取得客户端的输出信息
编写TCP程序
编写服务器程序
import java.io.IOException;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Hello {
public static void main(String[] args) throws IOException {
ServerSocket server = null;
Socket client = null;
PrintStream out = null;
server = new ServerSocket(8889);
System.out.println("服务器运行,等待客户端连接");
client = server.accept();
String str = "HELLO";
out = new PrintStream(client.getOutputStream());
out.println(str);
out.close();
client.close();
server.close();
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-M4azSWf1-1645464825525)(C:/Users/30452/AppData/Roaming/Typora/typora-user-images/image-20220220213550615.png)]
编写客户端程序
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.Socket;
public class Hello2 {
public static void main(String[] args) throws Exception{
Socket client = null;
client = new Socket("localhost",8889);
BufferedReader buf = null;
buf = new BufferedReader(new InputStreamReader(client.getInputStream()));
String str = buf.readLine();
System.out.println("服务器输出:"+str);
client.close();
buf.close();
}
}