最近學了點Java網絡編程,多個客戶端實現實時通訊。java
項目分爲4個類 :消息類、消息類型類、服務器端類、客戶端類。編程
消息類中 包括 String的消息內容、消息發送者、消息傳達者,和int的消息類型。服務器
package WeiXinItsFather;網絡
import java.io.Serializable;socket
public class Message implements Serializable{
private String from;
private String to;
private String info;
private int type;
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 String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public Message(String from, String to, String info, int type) {
super();
this.from = from;
this.to = to;
this.info = info;
this.type = type;
}
@Override
public String toString() {
return "Message [from=" + from + ", to=" + to + ", info=" + info + ", type=" + type + "]";
}
public Message() {
}
}
ide
消息類型類 包括 兩個靜態int的變量,用於區別服務器處理客戶端登陸和發送操做函數
package WeiXinItsFather;this
public final class MessageType {
public static final int TYPE_LOGIN = 0x1;
public static final int TYPE_SEND = 0x2;
}
.net
服務器端類經過 容器Vector保存客戶端處理的線程,經過ExecutorService 建立線程池,而後建立一個用戶進程類UserThread 繼承自 Runnable,重載run()函數:經過對象流獲取消息對象,而後判斷消息類型,如果登陸則經過輸出流返回「歡迎你」,如果發送類型則獲取消息對象中的消息傳達者,而後經過遍歷容器中是否有「消息傳達者」的客戶端線程,有的話就將消息對象經過該線程的輸出流發送出去。線程
package WeiXinItsFather;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Executable;
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) {
Vector<UserThread> vector = new Vector<UserThread>();//保存客戶端處理的線程
ExecutorService es = Executors.newFixedThreadPool(5);
try {
ServerSocket server = new ServerSocket(6666);
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 s;
private Vector<UserThread> v;
private String name;
private ObjectInputStream ois;
private ObjectOutputStream oos;
private boolean flag = true;
public UserThread(Socket s, Vector<UserThread> v) {
this.s = s;
this.v = v;
v.add(this);
}
@Override
public void run() {
try {
System.out.println("客戶端已鏈接"+s.getInetAddress().getHostAddress());
ois = new ObjectInputStream(s.getInputStream());
oos = new ObjectOutputStream(s.getOutputStream());
while (flag) {
Message msg = (Message)ois.readObject(); //讀取輸入流對象
int type = msg.getType(); //獲取輸入流對象中的類型
switch (type) { //判斷輸入流的對象類型
case MessageType.TYPE_SEND: //類型是發送信息
String info = msg.getTo(); //獲取要送達消息的客戶名稱
UserThread ut; //建立一個用戶線程
/**
* 判斷 要送達消息的客戶名稱 是否存在(是否在vector中)
* 存在的話就把 發送消息的客戶的消息內容(ois)寫到 要送達消息的「客戶通道」(oos)
*/
for (int i = 0; i < v.size(); i++) {
ut = v.get(i);
if(info.equals(ut.name) && ut!=this) {
ut.oos.writeObject(msg);
break;
}
}
break;
case MessageType.TYPE_LOGIN://類型是登陸
name = msg.getFrom();
msg.setInfo("歡迎你:");
oos.writeObject(msg);
break;
}
}
ois.close();
oos.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
客戶端類:建立線程,經過Socket鏈接服務器端,建立登陸的消息對象,經過輸出流發送到服務器;而後建立一個讀輸入流的線程ReadInfoThread,重載run()函數,實現獲取輸入流的消息對象(服務器發送來的);而後建立發送類型的消息對象,經過輸出流發送給服務器端。
package WeiXinItsFather;
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;
import java.util.*;
public class Client {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
ExecutorService es = Executors.newSingleThreadExecutor();
try {
Socket s = new Socket("localhost",6666);
System.out.println("服務器鏈接成功");
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
System.out.println("請輸入:");
String name = input.nextLine();
Message msg = new Message(name,null,null,MessageType.TYPE_LOGIN);
oos.writeObject(msg);
msg = (Message)ois.readObject();
System.out.println(msg.getInfo()+msg.getFrom());
es.execute(new ReadInfoThread(ois));
boolean flag = true;
while (flag) {
msg = new Message();
System.out.println("To:");
msg.setTo(input.nextLine());
msg.setFrom(name);
msg.setType(MessageType.TYPE_SEND);
System.out.println("請輸入要發送的消息info:");
String info = input.nextLine();
msg.setInfo(info);
oos.writeObject(msg);
}
} catch (IOException | ClassNotFoundException e) {
// TODO: handle exception
}
}
}
class ReadInfoThread implements Runnable{
private ObjectInputStream in;
public ReadInfoThread(ObjectInputStream in) {
this.in = in;
}
private boolean flag = true ;
@Override public void run() { try { while(flag) { Message msg = (Message)in.readObject(); System.out.println("["+msg.getFrom()+"]"+msg.getInfo()); } if(in!=null) { in.close(); } } catch (IOException | ClassNotFoundException e) { // TODO: handle exception } } } 注:在網絡通信中,主機與客戶端若使用ObjectInputStream與ObjectOutputStream創建對象通信,必須注重聲明此兩個對象的順序。 如: 主機端先創建ObjectInputStream後創建ObjectOutputStream,則對應地客戶端要先創建ObjectOutputStream後創建ObjectInputStream,不然會形成兩方互相等待數據而致使死鎖。 緣由是創建ObjectInputStream對象是須要先接收必定的header數據,接收到這些數據以前會處於阻塞狀態。