Socket客户端套接字
// 构造方法
// 使用主机名和端口创建
public Socket(String host, int port)
// 成员方法
// 返回Socket的输入流
public InputStream getInputStream()
// 返回Socket的输出流
public OutputStream getOutputStream()
// 关闭Socket
public void close()
// 禁用Socket输出流(方法调用前的数据发送,之后的都终止发送)
public void shutdownOutput()
ServerSocket服务端套接字
// 构造方法
public ServerSocket(int port)
// 成员方法
// 监听并接受连接请求,返回Socket对象
public Socket accept()
举例
// 客户端
public class TCPClient {
public static void main(String[] args) {
Socket socket = new Socket("localhost", 6666);
OutputStream outputStream = socket.getOutputStream();
String msg = "Hello TCP/IP";
outputStream.write(msg.getBytes());
outputStream.close();
socket.close();
}
}
// 服务端
public class TCPServer {
public static void main(String[] args) {
// 创建ServerSocket,监听6666端口
ServerSocket serverSocket = new ServerSocket("6666");
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
byte[] bytes = new byte[1024];
int len = inputStream.read(bytes);
String msg = new String(bytes, 0, len);
System.out.println(msg);
inputStream.close();
socket.close();
serverSocket.close();
}
}
// Hello TCP/IP