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();
}
}
}
以上只能对一个用户进行管理 想要对多个进行管理就需要用到多线程了。