Socket 编程
客户端(Socket)
客户端(Socket)
public static void main(String[] args) throws IOException {
//设置发送给服务器的ip和端口号
Socket s=new Socket("127.0.0.1",6666);
//创建输出字节流
OutputStream os=s.getOutputStream();
//包装成数据输出流
DataOutputStream dos=new DataOutputStream(os);
//写入内容
dos.writeUTF("hello world");
}
服务端(ServerSocket)
public static void main(String[] args) throws IOException {
//创建ServerSocket并监听6666端口
ServerSocket ss=new ServerSocket(6666);
//无限循环,用于不断接收请求
while (true){
//调用accept方法,接受客户端连接对象,阻塞式方法(本连接不结束,其他连接无法被占用)
Socket s=ss.accept();
System.out.println("已连接");
//接收客户端传入的数据流
DataInputStream dis=new DataInputStream(s.getInputStream());
//阻塞式方法,客户不传消息,就一直堵塞,程序不能往下执行,直到有消息读入
String str=dis.readUTF();
System.out.println(str);
}
}