用基于TCP的网络编程实现单个用户登录功能的简单模拟

Person类:

存储用户登录的用户名和密码信息

import java.io.Serializable;

public class Person implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	
	
	private String name;
	private String password;
	
	public Person(String name, String password) {
		super();
		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;
	}	
}

客户端:

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Scanner;

public class UploadImgClient {

	public static void main(String[] args) throws IOException {
		//提醒并接收用户输入
		Scanner sc=new Scanner(System.in);
		System.out.print("用户名:");
		String name=sc.next();
		System.out.print("密码:");
		String password=sc.next();
		
		
		//连接服务器利用Socket创建输出流,并将对象输出到服务器
		Socket s=new Socket("192.168.51.179",10001);
		OutputStream os = s.getOutputStream();
		ObjectOutputStream oos=new ObjectOutputStream(os);
		oos.writeObject(new Person(name,password));
		
		
		//关闭输出流
		s.shutdownOutput();
		
		//利用Socket创建输入流,接收服务器验证信息
		InputStream is = s.getInputStream();
		DataInputStream dis=new DataInputStream(is);
		System.out.print(dis.readUTF());
		
		//关流
		dis.close();
		is.close();
		s.close();	
		
	}
}

服务器:

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;


public class UploadImgServer {

	public static void main(String[] args) throws IOException, ClassNotFoundException {
		System.out.println("服务器接收数据!");
		//连接客户端利用Socket创建输入流并接收数据
		ServerSocket ss=new ServerSocket(10001);
		Socket s = ss.accept();
		InputStream is = s.getInputStream();
		ObjectInputStream ois=new ObjectInputStream(is);
		Person p = (Person)ois.readObject();
		
		//关闭Socket输入流
		s.shutdownInput();
		
		//启动Socket输出流,将登陆成功或失败信息返回给客户端
		OutputStream os = s.getOutputStream();
		DataOutputStream dos=new DataOutputStream(os);
		
		//对接收到的数据进行判定
		if("lili".equals(p.getName())&&"123123".equals(p.getPassword())) {
			dos.writeUTF("登陆成功!");
		}else {
			dos.writeUTF("登陆失败!");
		}
		
		//关流
		s.shutdownOutput();
		ois.close();
		is.close();
		s.close();
		ss.close();
		
		
	}

}

猜你喜欢

转载自blog.csdn.net/pengzonglu7292/article/details/85074865
今日推荐