1、实体类
package com.wyq.client;
import java.io.Serializable;
public class User implements Serializable{
public String userName;
public String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(String userName, String password) {
super();
this.userName = userName;
this.password = password;
}
public User() {
super();
}
@Override
public String toString() {
return "User [userName=" + userName + ", password=" + password + "]";
}
}
2、客户端
package com.wyq.client;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class TestCli {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws UnknownHostException, IOException {
/**用于向服务器发送请求**/
//创建连接
Socket client = new Socket("92.168.56.1", 9000);
//创建输出流对象
// OutputStream os = client.getOutputStream();
//封装之后的连接要使用对象流
ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
//发送对象
oos.writeObject(getUseruser());//调用本类中获取用户对象的方法
//shutdown
client.shutdownOutput();
/**接收服务器的响应**/
DataInputStream dis = new DataInputStream(client.getInputStream());
System.out.println(dis.readUTF());
//阶段输入流
client.shutdownInput();
//关闭
client.close();
oos.close();
dis.close();
}
//使用类进行初始化参数
public static User getUseruser(){
System.out.println("请输入用户名:");
String userName = sc.next();
System.out.println("请输入密码:");
String password = sc.next();
//使用这种范式进行封装成对象
return new User(userName,password);
}
}
3、服务器端
package com.wyq.server;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class TestSer {
public static void main(String[] args) throws IOException, ClassNotFoundException {
System.out.println("服务器已经开启。。。");
/**[1]接收客户端的请求**/
ServerSocket server = new ServerSocket(9000);
//服务器监听
Socket client = server.accept();
//接收用户对象
ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
//向下转型
//也就是将内容解析出来
User user = (User) ois.readObject();
System.out.println("ip地址为:"+client.getInetAddress().getHostAddress()+"请求登录您的电脑。");
//截断输入流
client.shutdownInput();
String result = null;
if("bjsxt".equals(user.getUserName())&&"password".equals(user.getPassword())){
result= "登录成功";
}else{
result = "登录失败";
}
/**[2]对客户端作出响应**/
//要进行类型转换,将字符流转换成字节流进行发送
DataOutputStream dos = new DataOutputStream(client.getOutputStream());
//发送
dos.writeUTF(result);
//截断输出流
client.shutdownOutput();
//关闭所有流
client.close();
dos.close();
ois.close();
}
}