JAVA模拟客户机与服务器实现简易的TCP通讯
大致图解如下:
//客户机
/*socket:此类实现客户端套接字(也可以就叫“套接字”)。套接字是两台机器间通信的端点。
Socket(InetAddress address, int port) :
创建一个流套接字并将其连接到指定 IP 地址的指定端口号。
*/
import java.io.*;
import java.net.*;
public class TcpClient{
public static void main(String[] args){
Socket s;
try {
s = new Socket("127.0.0.1",80);
OutputStream os = s.getOutputStream(); //输出流接受输出字节并将这些字节发送到某个接收器。
InputStream is = s.getInputStream(); //字节输入流
byte[] buf = new byte[100]; //字节型数组
System.out.println("给服务器发消息");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));//输入流
String msg = br.readLine(); //readLine将其转换为字符后返回,读取一个文本行。
os.write(msg.getBytes()); //从指定的 byte 数组写入此输出流。
System.out.println("等待来自服务器的消息");
int len = is.read(buf); //从输入流中读取一定数量的字节,并将其存储在缓冲区数组 buf 中。返回len个字节数。
msg = new String(buf,0,len); //通过使用平台的默认字符集解码指定的 byte 子数组,构造一个新的 String。
System.out.println(msg);
s.close(); //关闭此端点。
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//服务器
/*ServerSocket此类实现服务器套接字。
服务器套接字等待请求通过网络传入。
它基于该请求执行某些操作,然后可能向请求者返回结果。
ServerSocket(int port):创建绑定到特定端口(端口号)的服务器套接字。*/
import java.io.*;
import java.net.*;
public class TcpServer{
public static void main(String[] args){
ServerSocket ss;
try {
ss = new ServerSocket(80);
System.out.println("waiting TcpClient connection.");
Socket s = ss.accept(); //侦听并接受到此套接字的连接。此方法在连接传入之前一直阻塞。
System.out.println("TcpClient connection success.");
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
byte[] buf = new byte[100];
System.out.println("等待来自客户端的消息");
int len = is.read(buf);
String msg = new String(buf,0,len);
System.out.println(msg);
System.out.println("给客户端发消息");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
msg = br.readLine();
os.write(msg.getBytes());
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
效果实现: