记下来,方便以后查看

User类

 package com.xujingyang.ThreadSocket;

 import java.io.Serializable;

 public class User implements Serializable {
private String name;
private int age; public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public int getAge() {
return age;
} public void setAge(int age) {
this.age = age;
} public User(String name, int age) {
super();
this.name = name;
this.age = age;
} public User() {
} @Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
} @Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
} @Override
public String toString() {
return "User [name=" + name + ", age=" + age + "]";
}
}

客户端类

package com.xujingyang.ThreadSocket;

import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.net.Socket; public class Client {
public static void main(String[] args) throws Exception {
Socket socket=new Socket("localhost", 9999);//监听端口 ObjectOutputStream out=new ObjectOutputStream(socket.getOutputStream());//包装对象流 out.writeObject(new User("小明", 21));//写入对象
socket.shutdownOutput();//关闭流的占用 //获取服务器发过来的消息
InputStream in = socket.getInputStream();
byte[] b=new byte[1024];
in.read(b);
System.out.println(new String(b,0,b.length)); //关闭流
in.close();
out.close();
socket.close(); }
}

服务器类

package com.xujingyang.ThreadSocket;

import java.net.ServerSocket;
import java.net.Socket; public class Server {
public static void main(String[] args) throws Exception {
ServerSocket socket=new ServerSocket(9999);//监听端口 //循环监听接收各个客户端连接
while (true) {
Socket client = socket.accept(); //开启多线程接受客户端信息
ThreadServer ts=new ThreadServer(client);
new Thread(ts).start();
} }
}

服务器多线程接收类

package com.xujingyang.ThreadSocket;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.Socket; /**
* 多线程接受用户登陆,把客户端连接对象传入作为成员变量
* @author 徐景洋
*/
public class ThreadServer implements Runnable { private Socket client; public ThreadServer(Socket client) {
this.client=client;
} @Override
public void run() {
try {
//包装对象接收流
ObjectInputStream in=new ObjectInputStream(client.getInputStream());
User user = (User) in.readObject();//读取对象 //比较是否符合标准.符合回答成功,否则失败
OutputStream out = client.getOutputStream();
if((new User("小明",21)).equals(user)){
out.write("登陆成功".getBytes());
System.out.println(user);
}else{
out.write("登陆失败".getBytes());
} client.shutdownOutput();
out.close();
in.close();
client.close(); } catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
} } }
05-15 02:32