/**
* 服务器端
* */
public class RegistServer {
public static void main(String[] args) {
try {
//1.建立一个服务器Socket(ServerSocket)绑定指定端口并开始监听
ServerSocket serverSocket=new ServerSocket(8800);
//2.使用accept()方法阻塞等待监听,获得新的连接
Socket socket=serverSocket.accept();
//3.获得输入流
InputStream is=socket.getInputStream();
//获得流:可以对对象进行反序列化
ObjectInputStream ois=new ObjectInputStream(is);
//获得输出流
OutputStream os=socket.getOutputStream();
PrintWriter pw=new PrintWriter(os);
//4.读取用户注册信息
User user=(User)ois.readObject();
System.out.println("用户注册信息如下");
System.out.println(user.getLoginName()+"---"+user.getLoginPwd()+"---"+user.getGender()+"---"+user.getEmail());
//给注册用户一个响应
String reply="恭喜您,注册成功!";
pw.write(reply);
pw.flush();
//5.关闭资源
pw.close();
os.close();
ois.close();
is.close();
socket.close();
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 客户端
* */
public class RegistClient {
public static void main(String[] args) {
try {
//1.建立客户端Socket连接,指定服务器的位置以及端口
Socket socket=new Socket("localhost",8800);
//2.得到Socket的读写流
OutputStream os=socket.getOutputStream();
//对象序列化流
ObjectOutputStream oos=new ObjectOutputStream(os);
//输入流
InputStream is=socket.getInputStream();
BufferedReader br=new BufferedReader(new InputStreamReader(is));
//3.利用流按照一定的协议对Socket进行读/写操作
User user=new User();
user.setLoginName("Tom");
user.setLoginPwd("123456");
user.setGender("男");
user.setEmail("tom@163.com");
oos.writeObject(user);
socket.shutdownOutput();
//接受服务器的响应并打印显示
String reply=null;
while(!((reply=br.readLine())==null)){
System.out.println("我是客户端,服务器的响应为:"+reply);
}
//4.关闭资源
br.close();
is.close();
oos.close();
os.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}