在上一篇中,我们学习了关于使用 Java 实现 Socket 简单编程,server 实现了读,client端实现了写,今天我们学习在 server 和 client 都实现各自的读写,这里涉及到 DataInputStream 和 DataOutputStream 两个工具类的使用。
Server
package org.example;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleServerRdAndWr {
public static void main(String[] args) throws IOException {
System.out.println("---server---");
// 1.指定端口,创建服务器
ServerSocket ss = new ServerSocket(8000);
// 2.等待客户端连接
Socket so = ss.accept();
// 3.IO操作
DataInputStream dis = new DataInputStream(so.getInputStream());
String data = dis.readUTF();
String username = "";
String password = "";
String[] datas = data.split("&");
for (String info: datas) {
String[] userInfo = info.split("=");
if (userInfo[0].equals("username")) {
username = userInfo[1];
System.out.println("用户名:" + username);
} else if (userInfo[0].equals("password")) {
password = userInfo[1];
System.out.println("password: " + password);
}
}
DataOutputStream dos = new DataOutputStream(so.getOutputStream());
if (username.equals("abc") && password.equals("123456")) {
dos.writeUTF("Login success!");
} else {
dos.writeUTF("Login fail!");
}
// 4.释放资源
dos.close();
dis.close();
so.close();
ss.close();
}
}
Client
package org.example;
import java.io.*;
import java.net.Socket;
public class SimpleClientRdAndWr {
public static void main(String[] args) throws IOException {
System.out.println("----------Client----------");
// 1.建立连接
Socket client = new Socket("Localhost", 8000);
// 2.IO操作
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入用户名:");
String uname=br.readLine();
System.out.print("请输入密码:");
String upwd=br.readLine();
DataOutputStream dos = new DataOutputStream(client.getOutputStream());
dos.writeUTF("username="+uname+"&password="+upwd);
dos.flush();
DataInputStream dis = new DataInputStream(client.getInputStream());
String msg = dis.readUTF();
System.out.println(msg);
// 3.释放资源
dis.close();
dos.close();
br.close();
client.close();
}
}
参考: