《用户类》========================================================
public class LoginInfo implements Serializable {
private String name;
private String password;
public LoginInfo() {
}
public LoginInfo(String name, String password) {
this.name = name;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
《客户端》========================================================
public class Client {
public static void main(String[] args) {
OutputStream outputStream=null;
ObjectOutputStream objectOutputStream=null;
Socket socket = null;
try {
Scanner input =new Scanner(System.in);
socket=new Socket("127.0.0.1",44);
System.out.println("输入用户名");
String name =input.next();
System.out.println("输入密码");
String passWard =input.next();
LoginInfo loginInfo = new LoginInfo(name, passWard);
outputStream=socket.getOutputStream();
objectOutputStream=new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(loginInfo);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (outputStream != null){
outputStream.close();
}
if (objectOutputStream != null){
objectOutputStream.close();
}
if (socket!=null){
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
《服务器》==============================================================
public class Server {
public static void main(String[] args) {
ServerSocket serverSocket = null;
System.out.println("服务器正在启动.....");
System.out.println("服务器端启动成功!");
try {
serverSocket = new ServerSocket(44);
while (true){
Socket socket = serverSocket.accept();//接受客户端的socket
ServerThread serverThread=new ServerThread(socket);
serverThread.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
《多线程》=============================================================
public class ServerThread extends Thread{
private Socket socket;
public ServerThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
try {
InputStream inputStream=socket.getInputStream();
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
LoginInfo loginInfo = (LoginInfo)objectInputStream.readObject();
if (loginInfo.getName().equals("admin")&&loginInfo.getPassword().equals("123456")){
System.out.println("登录成功!");
}else {
System.out.println("登录失败!");
}
objectInputStream.close();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}