Socket的基础编程(一)

1.Socket简介

        在计算机网络编程技术中,两个进程,或者说是两台计算机可以通过一个网络通信连接实现数据交换,这种通信链路的端点就被称为Socket。Socket会根据应用程序提供的相关信息,通过绑定IP及信息数据,将数据交给驱动程序向网络上发出去。

2.Socket通信原理


3.使用Socket编程实现用户登录

步骤:
1>建立连接
2>打开Socket关联的输入流 输出流
3>从数据流写入信息和读取信息
4>关闭所有的数据流和Socket

相关代码:

对UserBean对象序列化
public class UserBean implements Serializable {
	private static final long serialVersionUID = 1L;
	private String name;
	private String password;

	public UserBean() {
	};

	public UserBean(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;
	}
}
Socket服务端:
public class ServerClient {
	public static void main(String[] args) {
		try {
			ServerSocket ss = new ServerSocket(8800);
			Socket socket = ss.accept();
			InputStream is = socket.getInputStream();
			OutputStream os = socket.getOutputStream();
			// 反序列化
			ObjectInputStream ois = new ObjectInputStream(is);
			UserBean user = (UserBean) ois.readObject();
			if (!(user == null)) {
				System.out.println("我是服务器,客户登录信息:" + user.getName() + ",密码是:" + user.getPassword());
			}
			String reply = "欢迎" + user.getName() + ",登陆成功";
			os.write(reply.getBytes());
			// 关闭资源 
			ois.close();
			os.close();
			is.close();
		} catch (IOException e) {
			System.out.println("IOException" + e);
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			System.out.println("ClassNotFoundException" + e);
			e.printStackTrace();
		}
	}
}
Socket客户端:
public class UserClient {
	public static void main(String[] args) {
		try {
			Socket socket = new Socket("LocalHost", 8800);
			OutputStream os = socket.getOutputStream();
			InputStream is = socket.getInputStream();
			// 对象序列化
			ObjectOutputStream oos = new ObjectOutputStream(os);
			// 发送客户端登陆信息,向输出流写入信息
			UserBean bean = new UserBean();
			bean.setName("ZhangSan");
			bean.setPassword("123456");
			oos.writeObject(bean);
			socket.shutdownOutput();
			String reply = null;
			BufferedReader br = new BufferedReader(new InputStreamReader(is));
			while (!((reply = br.readLine()) == null)) {
				System.out.println("我是客户端,服务器的响应是:" + reply);
			}
			os.close();
			is.close();
		} catch (UnknownHostException e) {
			System.out.println("UnknownHostException" + e);
			e.printStackTrace();
		} catch (IOException e) {
			System.out.println("IOException" + e);
			e.printStackTrace();
		}
	}
}


以上只能对一个用户进行管理 想要对多个进行管理就需要用到多线程了。



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值