【项目报备 源码】【wap手机版小说源码】【seo博客源码引流】java 在线聊天源码_java在线聊天系统
1.java是线聊a线系统如何实现客服在线聊天功能的?
2.ç¨Javaå®ç°ä¸ä¸ªäººåå 个ä¸åç人ç§èï¼ç¨Socketå®ç°
3.Javaç®åè天ç¨åº
java是如何实现客服在线聊天功能的?
Java 实现在线客服聊天功能的具体方式会因具体实现技术和业务需求不同而异,以下是天源一个可能的实现思路:客户端和服务端之间的通信协议:在实现在线聊天功能的时候,需要考虑客户端和服务端之间的聊天通信协议。可以使用 WebSocket 协议,线聊a线系统项目报备 源码这是天源一种全双工通信协议,支持客户端和服务端之间的聊天实时通信。Java 提供了多个 WebSocket 实现,线聊a线系统比如 Tyrus、天源Jetty 和 Netty。聊天
实现服务端:在服务端实现在线聊天功能,线聊a线系统需要创建 WebSocket 服务器,天源wap手机版小说源码并实现消息处理逻辑。聊天在 Java 中,线聊a线系统可以使用 Java WebSocket API,天源该 API 提供了 javax.websocket 包中的聊天类和接口,可以方便地创建 WebSocket 服务器和处理 WebSocket 消息。seo博客源码引流
在服务端,需要实现 WebSocket 端点(Endpoint),处理客户端连接、断开连接以及收发消息等操作。可以通过扩展 javax.websocket.Endpoint 类,现代信号处理教程源码重写 onOpen、onClose 和 onMessage 方法来处理相应的操作。
实现客户端:在客户端实现在线聊天功能,需要创建 WebSocket 客户端,并实现消息处理逻辑。同花顺均价线公式源码Java 提供了多个 WebSocket 客户端实现,比如 Tyrus、Jetty 和 Netty。
在客户端,可以使用 Java WebSocket API 提供的 javax.websocket 包中的类和接口来实现 WebSocket 客户端。需要使用 javax.websocket.ClientEndpoint 注解来标记客户端类,并使用 javax.websocket.Session 类来处理客户端连接、断开连接以及收发消息等操作。
存储聊天记录:在实现在线聊天功能时,需要考虑如何存储聊天记录。可以使用数据库或者文件等方式存储聊天记录,具体实现可以依据具体业务需求。
以上是一种可能的实现思路,实现在线聊天功能需要考虑很多具体细节,包括客户端和服务端的具体实现、消息处理逻辑、聊天记录存储等。
ç¨Javaå®ç°ä¸ä¸ªäººåå 个ä¸åç人ç§èï¼ç¨Socketå®ç°
package API_Day;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
/
*** æ§å¶å°è天ç¨åº
* 客æ·ç«¯åºç¨ç¨åº
* @author Jacob
*
*/
public class chatClient
{
//客æ·ç«¯ç¨äºä¸æå¡ç«¯è¿æ¥çSocket
private Socket clientSocket;
/
*** æé æ¹æ³ï¼å®¢æ·ç«¯åå§å
*/
public chatClient()
{
try
{
/
** socket(String host, int port)
* å°åï¼ IPå°åï¼ç¨æ¥å®ä½ç½ç»ä¸ç计ç®æº
* 端å£ï¼ ç¨æ¥æ¾å°è¿ç«¯è®¡ç®æºä¸ç¨æ¥è¿æ¥çæå¡ç«¯åºç¨ç¨åº
*/
clientSocket = new Socket("localhost",);
}
catch (Exception e)
{
e.printStackTrace();
}
}
/
*** 客æ·ç«¯æµç§°éªè¯æ¹æ³
* @param 为Scanner
*/
private void inputNickName(Scanner scan) throws Exception
{
String nickName = null;
//å建è¾åºæµ
PrintWriter pw = new PrintWriter(
new OutputStreamWriter(clientSocket.getOutputStream(),
"UTF-8"),true);
//å建è¾å ¥æµ
BufferedReader br = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream(),"UTF-8"));
while(true)
{
System.out.println("请å建æ¨çæµç§°ï¼");
nickName = scan.nextLine();
if (nickName.trim().equals(""))
{
System.out.println("æµç§°ä¸å¾ä¸ºç©º");
}
else
{
pw.println(nickName);
String pass = br.readLine();
if(pass!=null&&!pass.equals("OK"))
{
System.out.println("æµç§°å·²ç»è¢«å ç¨ï¼è¯·æ´æ¢ï¼");
}
else
{
System.out.println("ä½ å¥½ï¼"+nickName+"å¯ä»¥å¼å§è天äº");
break;
}
}
}
}
/
** 客æ·ç«¯å¯å¨çæ¹æ³
*/
public void start()
{
try
{
/
** å建Scannerï¼è¯»åç¨æ·è¾å ¥å 容
* ç®çæ¯è®¾ç½®å®¢æ·ç«¯çæµç§°
*/
Scanner scanner = new Scanner(System.in);
inputNickName(scanner);
/
** å°ç¨äºæ¥æ¶æå¡å¨ç«¯åéè¿æ¥çä¿¡æ¯ç线ç¨å¯å¨
*/
Runnable run = new GetServerMsgHandler();
Thread t = new Thread(run);
t.start();
/
** 建ç«è¾åºæµï¼ç»æå¡ç«¯åä¿¡æ¯
*/
OutputStream os = clientSocket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os,"UTF-8");
PrintWriter pw = new PrintWriter(osw,true);
while(true)
{
pw.println(scanner.nextLine());
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if(clientSocket !=null)
{
try
{
clientSocket.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}
/
*** 该线ç¨ä½ç¨æ¥å¾ªç¯è¯»åæå¡ç«¯åéè¿æ¥çä¿¡æ¯
* 并è¾åºå°å®¢æ·ç«¯çæ§å¶å°
* @param args
*/
class GetServerMsgHandler implements Runnable
{
@Override
public void run()
{
try
{
InputStream is = clientSocket.getInputStream();
InputStreamReader isr = new InputStreamReader(is,"UTF-8");
BufferedReader br = new BufferedReader(isr);
String msgString = null;
while((msgString = br.readLine())!= null)
{
System.out.println("æå¡ç«¯æ示ï¼"+ msgString);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
public static void main(String[] args)
{
chatClient client = new chatClient();
client.start();
}
}
package API_Day;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/
*** æ§å¶å°è天ç¨åº
* æå¡ç«¯åºç¨ç¨åº
* @author Jacob
*
*/
public class chatServer
{
/
*** ServerSocket æ¯è¿è¡å¨æå¡ç«¯çSocket
* ç¨æ¥çå¬ç«¯å£ï¼çå¾ å®¢æ·ç«¯çè¿æ¥ï¼
* ä¸æ¦è¿æ¥æåå°±ä¼è¿åä¸è¯¥å®¢æ·ç«¯éä¿¡çSocket
*/
private ServerSocket serverSocket;
/
*** å建线ç¨æ± æ¥ç®¡ç客æ·ç«¯çè¿æ¥çº¿ç¨
* é¿å ç³»ç»èµæºè¿åº¦æµªè´¹
*/
private ExecutorService threadPool;
/
*** 该å±æ§ç¨æ¥åæ¾å®¢æ·ç«¯ä¹é´ç§èçä¿¡æ¯
*/
private Map<String,PrintWriter> allOut;
/
*** æé æ¹æ³ï¼æå¡ç«¯åå§å
*/
public chatServer()
{
try
{
/
** å建ServerSocketï¼å¹¶ç³è¯·æå¡ç«¯å£
* å°æ¥å®¢æ·ç«¯å°±æ¯éè¿è¯¥ç«¯å£è¿æ¥æå¡ç«¯ç¨åºç
*/
serverSocket = new ServerSocket();
/
** åå§åMapéåï¼åæ¾å®¢æ·ç«¯ä¿¡æ¯
*/
allOut = new HashMap<String, PrintWriter>();
/
** åå§å线ç¨æ± ï¼è®¾ç½®çº¿ç¨çæ°é
*/
threadPool = Executors.newFixedThreadPool();
/
** åå§åç¨æ¥åæ¾å®¢æ·ç«¯è¾åºæµçéåï¼
* æ¯å½ä¸ä¸ªå®¢æ·ç«¯è¿æ¥ï¼å°±ä¼å°è¯¥å®¢æ·ç«¯çè¾åºæµåå ¥è¯¥éåï¼
* æ¯å½ä¸ä¸ªå®¢æ·ç«¯æå¼è¿æ¥ï¼å°±ä¼å°éåä¸è¯¥å®¢æ·ç«¯çè¾åºæµå é¤ï¼
* æ¯å½è½¬åä¸æ¡ä¿¡æ¯ï¼å°±è¦éåéåä¸çææè¾åºæµ(å ç´ )
* å æ¤è½¬åçé¢çé«äºå®¢æ·ç«¯ç»å ¥ç»åºçé¢çï¼
* è¿æ¯åºè¯¥ä½¿ç¨ArrayListæ¥åå¨å ç´ ï¼ä» é群èï¼ç§èä¸è¡
* allOut = new ArrayList<PrintWriter>();
*/
}
catch (Exception e)
{
e.printStackTrace();
}
}
/
** å°å®¢æ·ç«¯çä¿¡æ¯ä»¥Mapå½¢å¼åå ¥éåä¸
*/
private void addOut(String key,PrintWriter value)
{
synchronized(this)
{
allOut.put(key, value);
}
}
/
** å°ç»å®çè¾åºæµä»å ±äº«éåä¸å é¤
* åæ°ä¸ºå®¢æ·ç«¯nickName,ä½ä¸ºMapçkeyé®
*/
private synchronized void removeOut(String key)
{
allOut.remove(key);
System.out.println("å½åå¨çº¿äººæ°ä¸ºï¼"+ allOut.size());
}
/
** å°ç»å®çæ¶æ¯è½¬åç»ææ客æ·ç«¯
*/
private synchronized void sendMsgToAll(String message)
{
for(PrintWriter out: allOut.values())
{
out.println(message);
System.out.println("å½åå¨çº¿äººæ°ä¸ºï¼"+ allOut.size());
}
}
/
** å°ç»å®çæ¶æ¯è½¬åç»ç§èç客æ·ç«¯
*/
private synchronized void sendMsgToPrivate(String nickname,String message)
{
PrintWriter pw = allOut.get(nickname); //å°å¯¹åºå®¢æ·ç«¯çè天信æ¯ååºä½ä¸ºç§èå 容åéåºå»
if(pw!=null)
{
pw.println(message);
System.out.println("å½åå¨çº¿ç§è人æ°ä¸ºï¼"+ allOut.size());
}
}
/
*** æå¡ç«¯å¯å¨çæ¹æ³
*/
public void start()
{
try
{
while(true)
{
/
** çå¬ç«¯å£
*/
System.out.println("çå¾ å®¢æ·ç«¯è¿æ¥... ... ");
/
** Socket accept() è¿æ¯ä¸ä¸ªé»å¡æ¹æ³ï¼ä¼ä¸ç´å¨ç«¯å£è¿è¡çå¬
* ç´å°ä¸ä¸ªå®¢æ·ç«¯è¿æ¥ä¸ï¼æ¤æ¶è¯¥æ¹æ³ä¼å°ä¸è¿ä¸ªå®¢æ·ç«¯è¿è¡éä¿¡çSocketè¿å
*/
Socket socket = serverSocket.accept();
System.out.println("客æ·ç«¯è¿æ¥æåï¼ ");
/
** å¯å¨ä¸ä¸ªçº¿ç¨ï¼ç±çº¿ç¨æ¥å¤ç客æ·ç«¯ç请æ±ï¼è¿æ ·å¯ä»¥å次çå¬
* ä¸ä¸ä¸ªå®¢æ·ç«¯çè¿æ¥äº
*/
Runnable run = new GetClientMsgHandler(socket);
threadPool.execute(run); //éè¿çº¿ç¨æ± æ¥åé 线ç¨
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
/
*** 该线ç¨ä½ç¨æ¥å¤çç»å®çæä¸ä¸ªå®¢æ·ç«¯çæ¶æ¯ï¼å¾ªç¯æ¥æ¶å®¢æ·ç«¯åé
* çæ¯ä¸ä¸ªå符串ï¼å¹¶è¾åºå°æ§å¶å°
* @author Jacob
*
*/
class GetClientMsgHandler implements Runnable
{
/
** 该å±æ§æ¯å½å线ç¨å¤ççå ·ä½ç客æ·ç«¯çSocket
* @see java.lang.Runnable#run()
*/
private Socket socket;
/
** è·å客æ·ç«¯çå°åä¿¡æ¯
* private String hostIP;
*/
/
** è·å客æ·ç«¯çæµç§°
*/
private String nickName;
/
** å建æé æ¹æ³
*/
public GetClientMsgHandler(Socket socket)
{
this.socket = socket;
/
** è·åè¿ç«¯å®¢æ·çIpå°åä¿¡æ¯
* ä¿å客æ·ç«¯çIPå°åå符串
* InetAddress address = socket.getInetAddress();
* hostIP = address.getHostAddress();
*/
}
/
** å建å é¨ç±»æ¥è·åæµç§°
*/
private String getNickName() throws Exception
{
try
{
//æå¡ç«¯çè¾å ¥æµè¯»å客æ·ç«¯åéæ¥çæµç§°è¾åºæµ
InputStream iin = socket.getInputStream();
InputStreamReader isr =
new InputStreamReader(iin,"UTF-8");
BufferedReader bReader = new BufferedReader(isr);
//æå¡ç«¯å°æµç§°éªè¯ç»æéè¿èªèº«çè¾åºæµåéç»å®¢æ·ç«¯
OutputStream out = socket.getOutputStream();
OutputStreamWriter iosw =
new OutputStreamWriter(out,"UTF-8");
PrintWriter ipw = new PrintWriter(iosw,true);
//读å客æ·ç«¯åæ¥çæµç§°
String nameString = bReader.readLine();
while(true)
{
if(nameString.trim().length()==0)
{
ipw.println("FAIL");
}
if(allOut.containsKey(nameString))
{
ipw.println("FAIL");
}
else
{
ipw.println("OK");
return nameString;
}
nameString = bReader.readLine();
}
}
catch(Exception e)
{
throw e;
}
}
@Override
public void run()
{
PrintWriter pw = null;
try
{
/
** éè¿å®¢æ·ç«¯çSocketè·å客æ·ç«¯çè¾åºæµ
* ç¨æ¥å°æ¶æ¯åéç»å®¢æ·ç«¯
*/
OutputStream os = socket.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os,"UTF-8");
pw = new PrintWriter(osw,true);
/
** å°å®¢æ·æµç§°åå ¶æ说çè¯ä½ä¸ºå ç´ åå ¥å ±äº«éåHashMapä¸
*/
nickName = getNickName();
addOut(nickName, pw);
Thread.sleep();
/
** æå¡ç«¯éç¥ææ客æ·ç«¯ï¼æç¨æ·ç»å½
*/
sendMsgToAll("[ç³»ç»éç¥]ï¼æ¬¢è¿**"+nickName+"**ç»éè天室!");
/
** éè¿å®¢æ·ç«¯çSocketè·åè¾å ¥æµ
* 读å客æ·ç«¯åéæ¥çä¿¡æ¯
*/
InputStream is = socket.getInputStream();
InputStreamReader isr = new InputStreamReader(is,"UTF-8");
BufferedReader br = new BufferedReader(isr);
String msgString = null;
while((msgString = br.readLine())!=null)
{
//éªè¯æ¯å¦æ¯ç§è
if(msgString.startsWith("@"))
{
/
** ç§èæ ¼å¼ï¼@æµç§°ï¼å 容
*/
int index = msgString.indexOf(":");
if(index >=0)
{
//è·åæµç§°
String name = msgString.substring(1,index);
String info = msgString.substring(index+1,msgString.length());
info = nickName + "å¯¹ä½ è¯´ï¼"+ info;
//å°ç§èä¿¡æ¯åéåºå»
sendMsgToPrivate(name, info);
//æå¡ç«¯ä¸å¨å¹¿æç§èçä¿¡æ¯
continue;
}
}
/
** éåææè¾åºæµï¼å°è¯¥å®¢æ·ç«¯åéçä¿¡æ¯è½¬åç»ææ客æ·ç«¯
*/
System.out.println(nickName+"说ï¼"+ msgString);
sendMsgToAll(nickName+"说ï¼"+ msgString);
}
}
catch (Exception e)
{
/
** å 为Winç³»ç»ç¨æ·ç客æ·ç«¯æå¼è¿æ¥åï¼br.readLine()æ¹æ³è¯»å
* ä¸å°ä¿¡æ¯å°±ä¼æåºå¼å¸¸ï¼èLinuxç³»ç»ä¼æç»åénullï¼
* å æ¤è¿éå°±ä¸å¨å°æè·çå¼å¸¸æåºäºã
*/
}
finally
{
/
** å½æ§è¡å°æ¤å¤æ¶ï¼è¯´æ客æ·ç«¯å·²ç»ä¸æå¡ç«¯æå¼è¿æ¥
* åå°è¯¥å®¢æ·ç«¯åå¨å ±äº«éåä¸çè¾åºæµå é¤
*/
removeOut(nickName);
/
** éç¥ææ客æ·ç«¯ï¼ææ客æ·å·²ç»ä¸çº¿
*/
sendMsgToAll("[ç³»ç»éç¥]ï¼"+nickName + "å·²ç»ä¸çº¿äºã");
/
** å ³ésocketï¼åéè¿Socketè·åçè¾å ¥è¾åºæµä¹ä¸åå ³éäº
*/
if(socket!=null)
{
try
{
socket.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args)
{
chatServer server = new chatServer();
server.start();
}
}
æçä½ä¸ï¼ä¾ä½ åè
Javaç®åè天ç¨åº
package com.kum.im.hrserver.test;
import java.net.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.awt.*;
import java.awt.event.*;
public class ChatClient {
private SocketChannel sc = null;
private String name = null;
private Frame f;
private TextArea ta;
private TextField tf;
private boolean runnable = true;
public static void main(String[] args){
ChatClient cc = new ChatClient();
cc.createUI();
cc.inputName();
cc.connect();
new ReceiveThread(cc,cc.getTextArea()).start();
}
public SocketChannel getSc(){
return sc;
}
public void setName(String name){
this.name = name;
}
public TextArea getTextArea(){
return ta;
}
public TextField getTextField(){
return tf;
}
public boolean getRunnable(){
return runnable;
}
public void stop(){
runnable = false;
}
public void shutDown(){
try{
sc.write(ByteBuffer.wrap("bye".getBytes("UTF-8")));
ta.append("Exit in 5 seconds!");
this.stop();
Thread.sleep();
sc.close();
}catch(Exception e){
e.printStackTrace();
}
System.exit(0);
}
public void createUI(){
f = new Frame("Client");
ta = new TextArea();
ta.setEditable(false);
tf = new TextField();
Button send = new Button("Send");
Panel p = new Panel();
p.setLayout(new BorderLayout());
p.add(tf,"Center");
p.add(send,"East");
f.add(ta,"Center");
f.add(p,"South");
MyClientListener listener = new MyClientListener(this);
send.addActionListener(listener);
tf.addActionListener(listener);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
ChatClient.this.shutDown();
}
});
f.setSize(,);
f.setLocation(,0);
f.setVisible(true);
tf.requestFocus();
}
public boolean connect(){
try{
sc = SocketChannel.open();
//"zlg"为ç®æ 计ç®æºå
InetSocketAddress isa = new InetSocketAddress("..1.",);
sc.connect(isa);
sc.configureBlocking(false);
sc.write(ByteBuffer.wrap(name.getBytes("UTF-8")));
}catch(Exception e){
e.printStackTrace();
}
return true;
}
public void inputName(){
String name = javax.swing.JOptionPane.showInputDialog("Input Your Name:");
this.setName(name);
f.setTitle(name);
}
}
class MyClientListener implements ActionListener{
private ChatClient client;
public MyClientListener(ChatClient client){
this.client = client;
}
public void actionPerformed(ActionEvent e){
TextField tf = client.getTextField();
String info = tf.getText();
if(info.equals("bye")){
client.shutDown();
}else{
try{
client.getSc().write(ByteBuffer.wrap(info.getBytes("UTF-8")));
}catch (Exception e1) {
e1.printStackTrace();
}
}
tf.setText("");
tf.requestFocus();
}
}
class ReceiveThread extends Thread{
private ChatClient client;
private TextArea ta;
public ReceiveThread(ChatClient client,TextArea ta){
this.client = client;
this.ta = ta;
}
public void run(){
SocketChannel sc = client.getSc();
ByteBuffer byteBuffer = ByteBuffer.allocate();
CharBuffer charBuffer = null;
Charset charset = Charset.forName("UTF-8");
CharsetDecoder decoder = charset.newDecoder();
String msg = null;
int n = 0;
try{
while(client.getRunnable()){
n = sc.read(byteBuffer);
if(n>0){
byteBuffer.flip();
charBuffer = decoder.decode(byteBuffer);
msg = charBuffer.toString();
ta.append(msg + "\n");
}
byteBuffer.clear();
Thread.sleep();
}
}catch(Exception e){
e.printStackTrace();
System.exit(0);
}
}
}
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.net.*;
import java.util.*;
public class ICQServer {
private Selector selector = null;
private ServerSocketChannel ssc = null;
//æå¡å¨ç«¯é信端å£å·
private int port = ;
//å¨çº¿ç¨æ·å表
private Hashtable<String, SocketChannel> userList = null;
public ICQServer() { }
public ICQServer(int port) {
this.port = port;
}
//åå§åæå¡å¨
public void init() {
try {
//å建éæ©å¨å¯¹è±¡
selector = Selector.open();
//å建ServerSocketChannel
ssc = ServerSocketChannel.open();
//设置ServerSocketChannel为éé»å¡æ¨¡å¼
ssc.configureBlocking(false);
InetAddress ip = InetAddress.getLocalHost();
System.out.println("主æºå°å --------> " + ip);
InetSocketAddress isa = new InetSocketAddress(ip, port);
//å°ä¸æ¬ééç¸å ³çæå¡å¨å¥æ¥å对象ç»å®å°æå®å°åå端å£
ssc.socket().bind(isa);
//å建å¨çº¿ç¨æ·å表
userList = new Hashtable<String, SocketChannel> ();
}
catch (IOException e) {
System.out.println("åå§åæå¡å¨æ¶å¼å¸¸ï¼åå --------> " + e.getMessage());
}
}
//å¯å¨æå¡å¨
public void start() {
try {
//å°ServerSocketChannel注åå°Selectorä¸ï¼åå¤æ¥æ¶æ°è¿æ¥è¯·æ±
SelectionKey acceptKey = ssc.register(selector, SelectionKey.OP_ACCEPT);
SocketChannel sc;
int n;
String name; //ç¨æ·å
String msg; //ç¨æ·åè¨ä¿¡æ¯
while (true) {
//éæ©å½åææå¤äºå°±ç»ªç¶æçééæ对åºçéæ©é®,并å°è¿äºé®ç»æå·²éæ©é®é
n = selector.select(); //n为已éæ©é®éä¸é®ç个æ°
if (n > 0) {
//è·åæ¤éæ©å¨çå·²éæ©é®éã
Set readyKeys = selector.selectedKeys();
Iterator it = readyKeys.iterator();
//éåå½åå·²éæ©é®é
while (it.hasNext()) {
SelectionKey key = (SelectionKey) it.next();
//ä»å½åå·²éæ©é®éä¸ç§»é¤å½åé®ï¼é¿å éå¤å¤ç
it.remove();
//å¦æå½åé®å¯¹åºçééå·²åå¤å¥½æ¥åæ°çå¥æ¥åè¿æ¥
if (key.isAcceptable()) {
//è·åå½åé®å¯¹åºçå¯éæ©ééï¼ServerSocketChannelï¼
ssc = (ServerSocketChannel) key.channel();
//æ¥æ¶æ°çå¥æ¥åè¿æ¥è¯·æ±ï¼è¿åæ°å»ºçSocketChannel
sc = (SocketChannel) ssc.accept();
//å¦æææ°ç¨æ·æ¥å ¥
if (sc != null) {
//æ¥æ¶æ°ä¸çº¿ç¨æ·å§å
name = readMessage(sc);
//设置æ°å»ºçSocketChannel为éé»å¡æ¨¡å¼
sc.configureBlocking(false);
//å°æ°å»ºçSocketChannel注åå°Selectorä¸ï¼åå¤è¿è¡æ°æ®"å"æä½ï¼
//并å°å½åç¨æ·å以é件çæ¹å¼é带记å½å°æ°å»ºçéæ©é®ä¸ã
SelectionKey newKey = sc.register(selector,
SelectionKey.OP_WRITE, name);
//å°æ°ä¸çº¿ç¨æ·ä¿¡æ¯å å ¥å°å¨çº¿ç¨æ·å表
userList.put(name, sc);
//åé"æ°ç¨æ·ä¸çº¿"éç¥
transmitMessage(name + " in!", "--Server Info--");
}
}
//å¦åï¼å¦æå½åé®å¯¹åºçééå·²åå¤å¥½è¿è¡"å"æä½
else if (key.isWritable()) {
//è·åå½åé®å¯¹åºçå¯éæ©ééï¼SocketChannelï¼
sc = (SocketChannel) key.channel();
//æ¥æ¶è¯¥ééç¸åºç¨æ·çåè¨ä¿¡æ¯
msg = readMessage(sc);
//è·åéæ©é®ä¸é带记å½çå½åç¨æ·å
name = key.attachment().toString();
//å¦æç¨æ·æåºè¦ä¸çº¿
if (msg.equals("bye")) {
//ä»å¨çº¿ç¨æ·å表ä¸ç§»é¤å½åç¨æ·
userList.remove(name);
//注éå½åéæ©é®å¯¹åºç注åå ³ç³»
key.cancel();
//å ³éå½åå¯éæ©éé
sc.close();
//åé"ç¨æ·ä¸çº¿"éç¥
transmitMessage(name + " out!", "--Server Info--");
}
//å¦åï¼å¦ææ¥æ¶å°çç¨æ·åè¨ä¿¡æ¯é空ï¼""ï¼
else if (msg.length() > 0) {
//转åç¨æ·åè¨ä¿¡æ¯
transmitMessage(msg, name);
}
}
}
}
//延æ¶å¾ªç¯ï¼éä½æå¡å¨ç«¯å¤çè´è·
Thread.sleep();
}
}
catch (Exception e) {
System.out.println("å¯å¨æå¡å¨æ¶å¼å¸¸ï¼åå --------> " + e.getMessage());
}
}
//转åç¨æ·åè¨ä¿¡æ¯
public void transmitMessage(String msg, String name) {
try {
ByteBuffer buffer = ByteBuffer.wrap( (name + ":" + msg).getBytes("UTF-8"));
//å°åèæ°ç»å è£ å°ç¼å²åºä¸
Collection channels = userList.values();
SocketChannel sc;
for (Object o : channels) {
sc = (SocketChannel) o;
sc.write(buffer);
//å°ç¼å²åºæ°æ®åå ¥è天é¢æ¿(TextArea)
buffer.flip();
//å°ç¼å²åºByteBufferçæéå¼è®¾ç½®ä¸ºå½åæ°æ®å®é 大å°ï¼å°ç¼å²åºçå¼è®¾ç½®ä¸º0
}
}
catch (Exception e) {
System.out.println("转åç¨æ·åè¨ä¿¡æ¯æ¶å¼å¸¸ï¼åå --------> " + e.getMessage());
}
}
//æ¥æ¶ç¨æ·åè¨ä¿¡æ¯
public String readMessage(SocketChannel sc) {
String result = null;
int n = 0;
ByteBuffer buf = ByteBuffer.allocate();
try {
n = sc.read(buf);
buf.flip();
Charset charset = Charset.forName("UTF-8");
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charBuffer = decoder.decode(buf);
result = charBuffer.toString();
}
catch (IOException e) {
System.out.println("æ¥æ¶ç¨æ·åè¨ä¿¡æ¯æ¶å¼å¸¸ï¼åå --------> " + e.getMessage());
}
return result;
}
public static void main(String args[]) {
ICQServer server = new ICQServer();
server.init();
server.start();
}
}