聊java
1. java聊天小程序
汗,LZ真是牛,這可不是一個小程序,怎麼可能全部代碼貼出來,也沒工夫寫額,以前在學校我做過,我把我的思路給你好了,首先寫出服務端和客戶端,多線程實現收發,支持點對點聊天,如果這些LZ不會,那就先去看看基礎吧,在此基礎上,創建登錄用戶類,有用戶ID(String),昵稱和socket屬性,一個房間管理類,用來管理私聊,群聊或者2個以上人的聊天,有一個MAP屬性,以聊天者ID相加的值為建,以保存所有聊天者socket的List為值,其中群聊是MAP的默認屬性,登陸一個用戶,value就添加他socket,當用戶選擇一個人私聊,或者幾個人群聊時,MAP創建相應的映射,就這樣了,當時我是全部實現了,但在關閉socket時有些問題。
具體邏輯和其中BUG,自己調和寫吧,例如用ID相加為建有時會有問題。
2. 高手進,java實現聊天功能
。。。這個我以前也遇到過、不過我是用C#寫的、不過後來也有java的、你可以、使用Swing做的簡單界面,及使用Socket套接字實現簡單聊天 。。。。。。但是、我不知道你問的是C/S模式還是B/S 模式?
其中、B/S模式可以用Servlet來實現,思路是通過Context上下文綁定參數實現
而C/S模式的,是通過RMI遠程調用的方法實現的。。。先給你個C/S模式的核心代碼。。。import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;public class Server extends JFrame
{
public static void main(String [] args)
{
Server server=new Server();
//設定框架的關閉方式
server.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//顯示框架
server.setVisible(true);
server.pack();
CreateServer cs=new CreateServer(server);
}
// 設定框架的寬度和高度
private static final int WIDTH=450;
private static final int HEIGHT=450;
// 聊天信息框
JTextArea mainArea=new JTextArea(12,35);
// 發送信息的填寫框
JTextArea sendArea=new JTextArea(5,30);
// 構造函數
public Server()
{
//定位框架
Toolkit kit=Toolkit.getDefaultToolkit();
Dimension screenSize=kit.getScreenSize();//獲取電腦當前解析度
int width=screenSize.width;
int height=screenSize.height;
int x=(width-WIDTH)/2;
int y=(height-HEIGHT)/2;
//設置窗口顯示位置
setLocation(x,y);
//設置框架大小
setSize(WIDTH,HEIGHT);
//設置標題
setTitle("小新新聊天伺服器");
//設置窗口的自定義大小
setResizable(false);
//在內容表格上創建3個面板並加入到內容表格
Container con=this.getContentPane();
JPanel labelPanel=new LabelPanel();
con.add(labelPanel,BorderLayout.NORTH);
JPanel contentPanel=new ContentPanel();
con.add(contentPanel,BorderLayout.CENTER);
JPanel sendPanel=new SendPanel();
con.add(sendPanel,BorderLayout.SOUTH);
}
//聊天窗口的標題面板
class LabelPanel extends JPanel
{
public LabelPanel()
{
Font font=new Font("Dialog",Font.BOLD,18);
JLabel label=new JLabel("歡迎使用小新新聊天伺服器");
label.setFont(font);
this.add(label);
}
}
// 聊天信息查看面板
//該面板內的區域為不可編輯區域
class ContentPanel extends JPanel
{
public ContentPanel()
{
FlowLayout fl=new FlowLayout(FlowLayout.CENTER);
this.setLayout(fl);
mainArea.setLineWrap(true);
mainArea.setEditable(false);
JScrollPane scrollPanel=new JScrollPane(mainArea);
this.add(scrollPanel);
}
}
// 填寫發送信息的面板
class SendPanel extends JPanel
{
public SendPanel()
{
//面板的組件之間水平分隔15像素,垂直間距10像素
FlowLayout layout=new FlowLayout(FlowLayout.LEFT,15,10);
this.setLayout(layout);
sendArea.setLineWrap(true);
JScrollPane scrollPanel=new JScrollPane(sendArea);
this.add(scrollPanel);
JButton send=new JButton("發送");
this.add(send);
//對發送按鈕注冊動作監聽器
send.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String msg=sendArea.getText();
if(!msg.equals(""))
{
mainArea.append("【伺服器】:"+msg+"\n");
sendArea.setText("");
CreateServer.sendMsg(msg);
}
else
{
return;
}
}
});
}
}
}
//創建伺服器ServerSocket的類
class CreateServer extends Thread
{
private Server server;
private static BufferedReader in=null;//存儲客戶端發送到伺服器的數據
private static PrintWriter out=null;//存儲伺服器發送到客戶端的數據
private Socket socket=null;//等待客戶端連接socket
private ServerSocket ss=null;//開啟伺服器socket連接
//構造函數
public CreateServer(Server s)
{
this.server=s;
try
{
ss=new ServerSocket(2345);
System.out.println("伺服器成功啟動...!");
socket=ss.accept();//等待客戶端請求
//獲取輸入到伺服器的數據
in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
//獲取輸出到客戶端的數據
out=new PrintWriter(socket.getOutputStream(),true);
out.println("你好!");
}
catch(Exception r)
{
r.printStackTrace();
}
this.start();//啟動線程
}
//實現信息發送到客戶端的發送方法
public static void sendMsg(String s)
{
try
{
out.println("【伺服器】:"+s+"\n");
}
catch(Exception e)
{
System.out.println("發送信息失敗...!!");
e.printStackTrace();
}
}
// 線程Thread類的run方法實現對客戶端發送來的數據監聽
//線程啟動後開始該方法,執行線程體
public void run()
{
String msg="";
while(true)
{
try
{
msg=in.readLine();
//Thread.sleep(500);//線程睡眠
}
catch (SocketException ex)
{
ex.printStackTrace();
break;
}
catch(IOException r)
{
r.printStackTrace();
break;
}
//若從客戶端獲取的信息不為空對象也不為空串
//則把信息顯示在聊天信息文本域
if(msg!=null && msg.trim()!="")
{
server.mainArea.append(msg+"\n");
}
}
}
}
3. 如何實現java聊天功能的技術用到了哪些
java聊天功能主要涉及網路編程,而網路通訊常用的就http,webservice,tcp,udp等協議,如果想用基於java的組件建議用mina.
4. Java 聊天小程序
不知道你為什麼要用這個
流
datainputstream
sin
=
new
datainputstream(system.in);
你程序沒反應是你讀的時候一直阻塞著。你用
bufferedreader試試
肯定有反應。
5. JAVA聊天程序中的一些問題(高分懸賞)
1.客戶端創建Socket時會被分配到一個唯一的窗口,客戶端連接到伺服器時,伺服器會應該用accept()函數創建一個專門的Socket接收來自A的信息,所以只要讓伺服器知道你是A,當伺服器受到別人發給A的包時直接讓這個專門的Socket發信息就會直接發給A了。順便說下伺服器的設計思路,伺服器應該用多線程實現,主線程只管接受新連接,來個新連接就創建一個Socket,然後直接把這個Socket傳給多線程類,繼續監聽。由多線程類來處理客戶端需求。
2.直接轉發
3.哪能一個用戶一個表呢...不確定長度的列可以用字元串加分隔符保存,如用戶分組可保存為:我的好友&陌生人&黑名單.....有點像QQ額
6. java聊天程序
伺服器端:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
public class Server extends JFrame implements ActionListener{
JPanel contentPane;
JLabel jLabel2 = new JLabel();
JTextField jTextField2 = new JTextField("4700");
JButton jButton1 = new JButton();
JLabel jLabel3 = new JLabel();
JTextField jTextField3 = new JTextField();
JButton jButton2 = new JButton();
JScrollPane jScrollPane1 = new JScrollPane();
JTextArea jTextArea1 = new JTextArea();
ServerSocket server = null;
Socket socket = null;BufferedReader instr =null;PrintWriter os=null ;
//Construct the frame
public Server() {
jbInit();
}
class MyThread extends Thread{//該線程負責接受數據
public void run(){
try{
while(true){
this.sleep(100);
instr= new BufferedReader(new InputStreamReader(socket.getInputStream()));
if(instr.ready()){ //檢查是否有數據
jTextArea1.append("客戶端: "+instr.readLine()+"\n");
}
}
}catch(Exception ex){}
}
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==jButton1){
int port=Integer.parseInt(jTextField2.getText().trim());
listenClient(port);
}
if(e.getSource()==jButton2){
String s=this.jTextField3.getText().trim();
sendData(s);
}
}
private void listenClient(int port){//偵聽
try{
if(jButton1.getText().trim().equals("偵聽")){
server = new ServerSocket(port);
jButton1.setText("正在偵聽...");
socket=server.accept();//等待,一直到客戶端連接才望下執行
sendData("已經成功連接。。。");
jButton1.setText("正在聊天...");
jTextArea1.append("客戶端已經連接到伺服器\n");
MyThread t=new MyThread();
t.start();
}
}catch(Exception ex){
}
}
private void sendData(String s){//發送數據
try{
os= new PrintWriter(socket.getOutputStream());
os.println(s);
os.flush();
if(!s.equals("已經成功連接。。。"))
this.jTextArea1.append("Server:"+s+"\n");
}catch(Exception ex){
}
}
//Component initialization
private void jbInit() {
contentPane = (JPanel) this.getContentPane();
contentPane.setLayout(null);
this.setSize(new Dimension(540, 340));
this.setTitle("伺服器");
jLabel2.setBounds(new Rectangle(22, 27, 72, 28));
jLabel2.setText("埠號");
jLabel2.setFont(new java.awt.Font("宋體", 0, 14));
jTextField2.setBounds(new Rectangle(113, 27, 315, 24));
jButton1.setBounds(new Rectangle(440, 28, 73, 25));
jButton1.setFont(new java.awt.Font("Dialog", 0, 14));
jButton1.setBorder(BorderFactory.createEtchedBorder());
jButton1.setActionCommand("jButton1");
jButton1.setText("偵聽");
jLabel3.setBounds(new Rectangle(23, 57, 87, 28));
jLabel3.setText("請輸入信息");
jLabel3.setFont(new java.awt.Font("宋體", 0, 14));
jTextField3.setBounds(new Rectangle(114, 60, 314, 24));
jTextField3.setText("");
jButton2.setText("發送");
jButton2.setActionCommand("jButton1");
jButton2.setBorder(BorderFactory.createEtchedBorder());
jButton2.setFont(new java.awt.Font("Dialog", 0, 14));
jButton2.setBounds(new Rectangle(440, 58, 73, 25));
jScrollPane1.setBounds(new Rectangle(23, 92, 493, 189));
contentPane.add(jTextField2, null);
contentPane.add(jButton1, null);
contentPane.add(jLabel3, null);
contentPane.add(jTextField3, null);
contentPane.add(jButton2, null);
contentPane.add(jScrollPane1, null);
contentPane.add(jLabel2, null);
jScrollPane1.getViewport().add(jTextArea1, null);
jButton1.addActionListener(this);
jButton2.addActionListener(this);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
try{
socket.close();
instr.close();
System.exit(0);
}catch(Exception ex){
}
}
});
}
public static void main(String arg[]){
JFrame.(true);
Server frm=new Server();
frm.setVisible(true);
}
}
客戶端:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.*;
import java.net.*;
public class Client extends JFrame implements ActionListener{
JPanel contentPane;
JLabel jLabel1 = new JLabel();
JTextField jTextField1 = new JTextField("127.0.0.1");
JLabel jLabel2 = new JLabel();
JTextField jTextField2 = new JTextField("4700");
JButton jButton1 = new JButton();
JLabel jLabel3 = new JLabel();
JTextField jTextField3 = new JTextField();
JButton jButton2 = new JButton();
JScrollPane jScrollPane1 = new JScrollPane();
JTextArea jTextArea1 = new JTextArea();
BufferedReader instr =null;
Socket socket = null;
PrintWriter os=null;
public Client() {
jbInit();
}
class MyThread extends Thread{
public void run(){
try{
os=new PrintWriter(socket.getOutputStream());
instr=new BufferedReader(new InputStreamReader(socket.getInputStream()));
while(true){
this.sleep(100);
if(instr.ready()){
jTextArea1.append("伺服器: "
+instr.readLine()+"\n");
}
}
}catch(Exception ex){
}
}
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==jButton1){
String ip=jTextField3.getText().trim();
int port=Integer.parseInt(jTextField2.getText().trim());
connectServer(ip,port);
}
if(e.getSource()==jButton2){
String s=this.jTextField3.getText().trim();
sendData(s);
}
}
private void connectServer(String ip,int port){//連接
try{
if(jButton1.getText().trim().equals("連接")){
jButton1.setText("連接伺服器...");
socket=new Socket(ip,port);
jButton1.setText("正在聊天");
MyThread t=new MyThread();
t.start();
}
}catch(Exception ex){
}
}
private void sendData(String s){//發送數據
try{
os = new PrintWriter(socket.getOutputStream());
os.println(s);
os.flush();
this.jTextArea1.append("Server:"+s+"\n");
}catch(Exception ex){
}
}
private void jbInit() {
contentPane = (JPanel) this.getContentPane();
jLabel1.setFont(new java.awt.Font("宋體", 0, 14));
jLabel1.setText("伺服器名稱");
jLabel1.setBounds(new Rectangle(20, 22, 87, 28));
contentPane.setLayout(null);
this.setSize(new Dimension(540, 340));
this.setTitle("客戶端");
jTextField1.setBounds(new Rectangle(114, 26, 108, 24));
jLabel2.setBounds(new Rectangle(250, 25, 72, 28));
jLabel2.setText("埠號");
jLabel2.setFont(new java.awt.Font("宋體", 0, 14));
jTextField2.setBounds(new Rectangle(320, 27, 108, 24));
jButton1.setBounds(new Rectangle(440, 28, 73, 25));
jButton1.setFont(new java.awt.Font("Dialog", 0, 14));
jButton1.setBorder(BorderFactory.createEtchedBorder());
jButton1.setActionCommand("jButton1");
jButton1.setText("連接");
jLabel3.setBounds(new Rectangle(23, 57, 87, 28));
jLabel3.setText("請輸入信息");
jLabel3.setFont(new java.awt.Font("宋體", 0, 14));
jTextField3.setBounds(new Rectangle(114, 60, 314, 24));
jButton2.setText("發送");
jButton2.setActionCommand("jButton1");
jButton2.setBorder(BorderFactory.createEtchedBorder());
jButton2.setFont(new java.awt.Font("Dialog", 0, 14));
jButton2.setBounds(new Rectangle(440, 58, 73, 25));
jScrollPane1.setBounds(new Rectangle(23, 92, 493, 189));
contentPane.add(jLabel1, null);
contentPane.add(jTextField1, null);
contentPane.add(jLabel2, null);
contentPane.add(jTextField2, null);
contentPane.add(jButton1, null);
contentPane.add(jLabel3, null);
contentPane.add(jTextField3, null);
contentPane.add(jButton2, null);
contentPane.add(jScrollPane1, null);
jScrollPane1.getViewport().add(jTextArea1, null);
jButton1.addActionListener(this);
jButton2.addActionListener(this);
this.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
try{
socket.close();instr.close();os.close();System.exit(0);
}catch(Exception ex){
}
}
});
}
public static void main(String arg[]){
JFrame.(true);
Client frm=new Client();
frm.setVisible(true);
}
}
先啟動伺服器端,偵聽埠,再啟動客戶端,就行了
7. 如何對基於java的聊天軟體開發系
關於聊天軟體定製開發的收費標准,取決於源碼中功能的復雜程度。 功能越復雜,社交軟體的成本就越高。 另外,社交軟體的開發不僅要滿足社交需求,我有一個明確的解決問題的思路! ~ 有兩種類型的結構:b/s 和 c/s 用於介面。 b/s是瀏覽器/伺服器的方式,以web的方式聊天。 c/s是client/server的方式,桌面程序的方式一般都是這種方式。 Java一般有三種類型的庫:桌面界面的awt/swing/swt。 最受歡迎的是swi
8. 如何用Java寫聊天軟體
做界面肯定要swing 然後結合Socket編寫網路程序 多個客戶端的話 要啟動線程來配置每個客戶端
9. 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(5000);
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(400,400);
f.setLocation(600,0);
f.setVisible(true);
tf.requestFocus();
}
public boolean connect(){
try{
sc = SocketChannel.open();
//"zlg"為目標計算機名
InetSocketAddress isa = new InetSocketAddress("192.168.1.43",8814);
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(2048);
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(500);
}
}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 = 8814;
//在線用戶列表
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(500);
}
}
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(1024);
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();
}
}