这玩意就是一个基于TCP的建议聊天室,有服务端与客户端。服务端负责对客户端的数据进行转发至另一个客户端。当然前提是每一个客户端连接服务器的时候需要提供一个用户名,也就是需要进行超简陋的登录。
Message是我们传递的数据,我们传递消息对象
MessageType 是一个用来标注消息类型的
import java.io.Serializable;
public class Message implements Serializable{
private String from;//消息发送者
private String to;//消息接收者
private int type;//消息类型
private String info;//发送的消息内容
public Message(){
}
public Message(String from, String to, int type, String info) {
this.from = from;
this.to = to;
this.type = type;
this.info = info;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}
type类
public final class MessageType {
public static final int TYPE_LOGIN = 0x1;//登录的消息类型
public static final int TYPE_SEND = 0x2; //发送的消息类型
}
先将用户处理的线程加入列表
更据消息类型做适当反馈,如果是发送消息,那么就直接遍历列表中的用户线程,对比线程的用户名是否与我们的发送对象相等,之后使用该用户线程的输出流发送msg对象,实现通信。
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Server {
//服务器端负责数据的中转
public static void main(String[] args) {
ExecutorService es = Executors.newFixedThreadPool(6);//线程池大小最多同时支持6个人聊天
Vector<UserThread> vector = new Vector<>();//存储客户端线程
try{
ServerSocket server = new ServerSocket(8888);
System.out.println("服务器已启动......");
while(true){
Socket socket = server.accept();
UserThread user = new UserThread(socket,vector);
es.execute(user);
}
}catch(IOException e){
e.printStackTrace();
}
}
}
class UserThread implements Runnable{
private Socket socket;
private Vector<UserThread> vector;
private String name;
private ObjectInputStream ois;
private ObjectOutputStream oos;
private boolean flag=true;
public UserThread(Socket socket, Vector<UserThread> vector) {
this.socket = socket;
this.vector = vector;
this.vector.add(this);
}
public UserThread() {
}
@Override
public void run() {
// TODO Auto-generated method stub
try{
System.out.println("[Host:"+socket.getInetAddress().getHostAddress()+"-连接]");
ois = new ObjectInputStream(socket.getInputStream());
oos = new ObjectOutputStream(socket.getOutputStream());
while(flag){
Message msg = (Message) ois.readObject();
int type = msg.getType();
switch(type){
case MessageType.TYPE_LOGIN:{
//登录
this.name = msg.getFrom();
msg.setInfo("欢迎你:"+this.name);
oos.writeObject(msg);
break;
}
case MessageType.TYPE_SEND:{
//发送消息
String sendto = msg.getTo();
for(UserThread user:vector){
if(sendto.equals(user.name)&&user!=this){
//寻找
user.oos.writeObject(msg);
System.out.println(this.name+"send message to"+msg.getTo()+"--success");
break;
}
else{
System.out.println(this.name+"send message to"+msg.getTo()+"--fail");
}
}
break;
}
}
}
oos.close();
ois.close();
}catch(IOException | ClassNotFoundException e){
// e.printStackTrace();
System.out.println("Closed"+name);
return;
}
}
}
消息接收
消息接受专门在开了一个子线程负责接收消息并展示
消息发送
这个的话我们直接在主线程当中进行发送即可
当客户端关闭后,我们在服务端的子线程必须关闭,否则继续运行会浪费内存。这里的话,在客户端关闭后,会在我们的服务端抛出IOException异常,那么我在在抛出异常后关闭即可。
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Client {
public static void main(String[] args) {
ExecutorService es = Executors.newSingleThreadExecutor();
Scanner input = new Scanner(System.in);
try{
Socket socket = new Socket("localhost",8888);
System.out.println("已连接至服务器");
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
//登录
System.out.print("请输入用户名:");
String username = input.nextLine();
Message msg = new Message(username,null,MessageType.TYPE_LOGIN,null);
oos.writeObject(msg);
msg = (Message)ois.readObject();
System.out.println(msg.getInfo());
//与其他用户接收发送交流消息
//读取其他用户的消息
// new Thread(new ReadInfoThread(ois)).start();
es.execute(new ReadInfoThread(ois));
//发送直接在主线程发送
boolean flag = true;
while(flag){
msg = new Message();
System.out.print("To:");
msg.setTo(input.nextLine());
msg.setFrom(username);
msg.setType(MessageType.TYPE_SEND);
System.out.print("\nmsg:");
msg.setInfo(input.nextLine());
oos.writeObject(msg);
}
}catch(IOException | ClassNotFoundException e){
e.printStackTrace();
}
}
}
class ReadInfoThread implements Runnable{
private ObjectInputStream ois;
private boolean flag = true;
public ReadInfoThread(ObjectInputStream ois){
this.ois = ois;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
while(flag){
Message msg=(Message)ois.readObject();
System.out.println();
System.out.println("From:["+msg.getFrom()+"]say:"+msg.getInfo());
System.out.print("To:");
}
if(ois!=null){
ois.close();
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}