思路
1:建立一个Map类,用来实现用户名和输入流的一一对应。
2:创建一个识别类,用来判断用户的输入类型 (私聊,公聊等)。
3:创建一个Server类,用来实现对client的接收,并在ServerThread类里面实现
4:穿件一个ServerThread类继承Thread,在里面实现
1,对用户输入数据类型的判读
2,实现登陆 ( map.put ), 传递私人或公聊信息;
3. 如果出错,移除该用户(map.remove) , 关闭传入的流,和创建的各种输入流
5:创建一个Client类,用来实现键盘的输入并处理后输入Server,在ClientThread类里面实现反馈
信息的输出。
6:创建一个ClientThread类,在该类实现对反馈信息的输出。
package com.MulThread;
public interface CrazyitProtocol {
int PROTOCOL_LEN = 2;
String MSG_ROUND = "@Y";
String USED_ROUND = "#$";
String LOGIN_ROUND = "^$";
String NAME_REP = "_!";
String PRIVATE_ROUND = "$$";
String SPLIT_SING = "-1";
String LOGIN_SUCCSEE = "##";
}
package com.MulThread;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
public class CrazyitMap<K, V> {
public Map<K, V> map = Collections.synchronizedMap(new HashMap<K, V>());
public synchronized void removeByValue(Object value) {
for (Object key : map.keySet()) {
if (map.get(key) == value) {
map.remove(key);
break;
}
}
}
public synchronized Set<V> valueSet() {
Set<V> result = new HashSet<V>();
map.forEach((key, value) -> result.add(value));
return result;
}
public synchronized K getKeyByvalue(V val) {
for (K key : map.keySet()) {
if (map.get(key) == val || map.get(key).equals(val)) {
return key;
}
}
return null;
}
public synchronized V put(K key, V value) {
for (V val : valueSet()) {
if (val.equals(value) && val.hashCode() == value.hashCode()) {
throw new RuntimeException("MyMap实例中不允许有重复value");
}
}
return map.put(key, value);
}
}
package com.MulThread;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private static final int SERVER_PORT = 30000;
// 用来保存每个对客户名字和对应输入流之间的对应关系
public static CrazyitMap<String, PrintStream> clients = new CrazyitMap<>();
public void init() {
try (ServerSocket ss = new ServerSocket(SERVER_PORT);) {
//利用死循环来不断接受用户的请求
while(true)
{
Socket socket = ss.accept();
new ServerThread(socket).start();
}
} catch (Exception e) {
// TODO: handle exception
System.out.println("服务器启动失败 , 是否端口 " + SERVER_PORT + " 已被占用 ?");
}
}
public static void main(String[] args) {
Server server = new Server();
server.init();
}
}
package com.MulThread;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket
public class ServerThread extends Thread {
private Socket socket;
BufferedReader br = null;
PrintStream ps = null;
//接受Socket
public ServerThread(Socket socket) {
this.socket = socket;
}
@Override
public void run() {
// TODO Auto-generated method stub
try {
//获取对应的输入流
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
ps = new PrintStream(socket.getOutputStream());
String line = null;
while ((line = br.readLine()) != null) {
//用户登陆
if (line.startsWith(CrazyitProtocol.USED_ROUND) && line.endsWith(CrazyitProtocol.USED_ROUND)) {
String userName = getRealMsg(line);
if(Server.clients.map.containsKey(userName)){
System.out.println("重复");
ps.println(CrazyitProtocol.NAME_REP);
}
else{
System.out.println("成功");
ps.println(CrazyitProtocol.LOGIN_SUCCSEE);
Server.clients.put(userName,ps);
}
}
//私聊
else if(line.startsWith(CrazyitProtocol.PRIVATE_ROUND)&&line.endsWith(CrazyitProtocol.PRIVATE_ROUND)){
String userAndMsg = getRealMsg(line);
String user = userAndMsg.split(CrazyitProtocol.SPLIT_SING)[0];
String msg = userAndMsg.split(CrazyitProtocol.SPLIT_SING)[1];
Server.clients.map.get(user).println(Server.clients.getKeyByvalue(ps) + "悄悄对你说" + msg);
}
//公聊
else
{
String msg = getRealMsg(line);
for(PrintStream clientPs : Server.clients.valueSet() )
{
clientPs.println(Server.clients.getKeyByvalue(ps) + "说:" + msg);
}
}
}
}
//捕捉到异常后,表明该Socket对应的客户端出现了问题
//所有程序将其对应的输出流从Map中删除
catch (IOException e) {
Server.clients.removeByValue(ps);
System.out.println(Server.clients.map.size());
try {
if (br != null) {
br.close();
}
if (ps != null) {
ps.close();
}
if (socket != null) {
socket.close();
}
} catch (Exception e2) {
// TODO: handle exception
e.printStackTrace();
}
}
}
//将读到的内容去掉前后的协议字符,恢复成真实数据
private String getRealMsg(String line) {
return line.substring(CrazyitProtocol.PROTOCOL_LEN,
line.length() - CrazyitProtocol.PROTOCOL_LEN);
}
}
package com.MulThread;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JOptionPane;
public class Client {
private static final int SERVER_PORT = 30000;
private Socket socket;
private PrintStream ps;
private BufferedReader brServer;
private BufferedReader keyIn;
public void init() throws Exception, Exception
{
try{
keyIn = new BufferedReader(new InputStreamReader(System.in));
socket = new Socket("127.0.0.1",SERVER_PORT);
ps = new PrintStream(socket.getOutputStream());
brServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String tip = "";
while(true)
{
String userName = JOptionPane.showInputDialog(tip + "输入用户名");
//发送用户名
ps.println(CrazyitProtocol.USED_ROUND + userName + CrazyitProtocol.USED_ROUND);
String result = brServer.readLine();
if(result.equals(CrazyitProtocol.NAME_REP))
{
tip = "用户名重复";
continue;
}
if(result.equals(CrazyitProtocol.LOGIN_SUCCSEE))
{
break;
}
}
}
catch(UnknownHostException ex){
System.out.println("找不到远程服务器,请确定服务器已经启动!");
closeRs();
System.exit(1);
}
}
public void closeRs()
{
try{
if(keyIn != null)
{
keyIn.close();
}
if(brServer != null)
{
brServer.close();
}
if(ps != null)
{
ps.close();
}
if(socket != null)
{
socket.close();
}
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
public void readAndSend()
{
try{
String line = null;
while((line = keyIn.readLine()) != null)
{
//如果发送的信息中有冒号 , 且以//开头,则认为想发送私聊信息
if(line.indexOf(":")>0 & line.startsWith("//"))
{
line = line.substring(2);
ps.println(CrazyitProtocol.PRIVATE_ROUND + line.split(":")[0]
+ CrazyitProtocol.SPLIT_SING + line.split(":")[1] + CrazyitProtocol.PRIVATE_ROUND);
}
else
{
ps.println(CrazyitProtocol.MSG_ROUND+line+CrazyitProtocol.MSG_ROUND);
}
}
}
catch(IOException ex)
{
System.out.println("网络通信异常!请重新登录");
closeRs();
System.exit(1);
}
new ClientThread(brServer).start();
}
public static void main(String[] args) throws Exception {
Client client = new Client();
client.init();
client.readAndSend();
}
}
package com.MulThread;
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.Buffer;
public class ClientThread extends Thread{
BufferedReader br = null;
public ClientThread(BufferedReader br)
{
this.br = br;
}
@Override
public void run() {
// TODO Auto-generated method stub
try{
String line = null;
while((line = br.readLine()) != null)
{
System.out.println(line);
}
}catch(IOException ex)
{
ex.printStackTrace();
}finally{
try{
if(br != null )
br.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
329

被折叠的 条评论
为什么被折叠?



