java聊天小程序
以下基於/IP協議:
16.聊天室伺服器端邏輯
//Debug.java
import java.util.*;
public class Debug {
public static String p(String s) {
System.out.println(s);
return s;
}
public static Object p(Object O) {
System.out.println(O.toString());
return O;
}
public static Object[] p(Object[] O) {
System.out.print("[");
String s = "";
for (Object o : O) {
System.out.print(s);
System.out.print(o.toString());
s = ",";
}
System.out.println("]");
return O;
}
public static int p(int i) {
System.out.println(i);
return i;
}
public static long p(long i) {
System.out.println(i);
return i;
}
public static Map.Entry p(Map.Entry l) {
System.out.println(l);
return l;
}
public static HashSet p(HashSet l) {
System.out.println(l);
return l;
}
public static HashMap p(HashMap l) {
System.out.println(l);
return l;
}
public static Map p(Map l) {
System.out.println(l);
return l;
}
public static LinkedHashSet p(LinkedHashSet l) {
System.out.println(l);
return l;
}
public static TreeSet p(TreeSet l) {
System.out.println(l);
return l;
}
public static Set p(Set l) {
System.out.println(l);
return l;
}
public static ArrayList p(ArrayList l) {
System.out.println(l);
return l;
}
public static LinkedList p(LinkedList l) {
System.out.println(l);
return l;
}
public static List p(List l) {
System.out.println(l);
return l;
}
}
//Service.java
import java.io.*;
import java.net.*;
import java.util.*;
public class Service extends Thread{
private Socket client=null;
private Server server=null;
public Service(Server server,Socket client){
this.server=server;
this.client=client;
}
public void run(){
try {
BufferedReader br=new BufferedReader(new InputStreamReader(client.getInputStream()));
while(true){
String str=br.readLine();
List<Socket> li=server.getLi();
for(Socket c:li){
if(!c.isClosed() && c.isConnected()){
OutputStream os=c.getOutputStream();
os.write((str+"\n").getBytes());
}else{
client.close();
server.getLi().remove(client);
break;
}
}
}
}catch (IOException e) {
e.printStackTrace();
}
}
}
//Server.java
import java.util.*;
import java.io.*;
import java.net.*;
public class Server {
private List<Socket> li=new ArrayList<Socket>();
private ServerSocket ss=null;
public List<Socket> getLi(){
return li;
}
public Server(int port){
try {
ss=new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}
public void start(){
while(true){
Socket s;
try {
s = ss.accept();
li.add(s);
new Service(this,s).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new Server(8888).start();
}
}
17.聊天室客戶端邏輯
//Debug.java
import java.util.*;
public class Debug {
public static String p(String s) {
System.out.println(s);
return s;
}
public static Object p(Object O) {
System.out.println(O.toString());
return O;
}
public static Object[] p(Object[] O) {
System.out.print("[");
String s = "";
for (Object o : O) {
System.out.print(s);
System.out.print(o.toString());
s = ",";
}
System.out.println("]");
return O;
}
public static int p(int i) {
System.out.println(i);
return i;
}
public static long p(long i) {
System.out.println(i);
return i;
}
public static Map.Entry p(Map.Entry l) {
System.out.println(l);
return l;
}
public static HashSet p(HashSet l) {
System.out.println(l);
return l;
}
public static HashMap p(HashMap l) {
System.out.println(l);
return l;
}
public static Map p(Map l) {
System.out.println(l);
return l;
}
public static LinkedHashSet p(LinkedHashSet l) {
System.out.println(l);
return l;
}
public static TreeSet p(TreeSet l) {
System.out.println(l);
return l;
}
public static Set p(Set l) {
System.out.println(l);
return l;
}
public static ArrayList p(ArrayList l) {
System.out.println(l);
return l;
}
public static LinkedList p(LinkedList l) {
System.out.println(l);
return l;
}
public static List p(List l) {
System.out.println(l);
return l;
}
}
//GetMessage.java
import javax.swing.*;
import java.io.*;
import java.net.*;
public class GetMessage extends Thread{
private JTextArea context=null;
private Socket s=null;
public GetMessage(JTextArea context,Socket s){
this.context=context;
this.s=s;
}
public void run(){
try {
BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
while(true){
String str=br.readLine();
String c=context.getText();
context.setText(c+"\n"+str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//Client.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class Client extends JFrame {
private String ip = "";
private int port = 0;
private Socket s = null;
private JTextArea context = new JTextArea(10, 10);
JScrollPane sp = new JScrollPane(context);
private JTextField say = new JTextField(10);
private Container c;
public Client(String ip, int port) {
c = this.getContentPane();
c.setLayout(new BorderLayout());
context.setEditable(false);
c.add(sp);
JPanel p = new JPanel();
p.add(BorderLayout.CENTER, say);
c.add(BorderLayout.SOUTH, p);
try {
s = new Socket(ip, port);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
say.addActionListener(new ActionListener() {
private void send(String str) {
try {
OutputStream os = s.getOutputStream();
os.write(str.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
public void actionPerformed(ActionEvent arg0) {
String str = say.getText();
send(str + "\n");
say.setText("");
}
});
new GetMessage(context, s).start();
this.setSize(300, 300);
this.setVisible(true);
this.setResizable(false);
}
public static void main(String[] args) {
String strIP = null;
try {
strIP = InetAddress.getLocalHost().getHostAddress().toString();
} catch (UnknownHostException e) {
e.printStackTrace();
}
new Client(strIP, 8888); //"127.0.0.1"
}
}
㈡ Java 聊天小程序
客戶端:
package clientsocket;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class Main {
private Socket s;
private DataInputStream dis;
private DataOutputStream dos;
private TextArea ta;
private TextField tf;
public static void main(String[] args) {
Main m=new Main();
m.createUI();
m.connect();
m.createThread();
}
public void connect(){
try{s=new Socket("127.0.0.1",8888);//127.0.0.1是你自己的ip號
dos=new DataOutputStream(s.getOutputStream());
dis=new DataInputStream(s.getInputStream());}
catch(IOException e){ e.printStackTrace();}
}
public void createUI(){
Frame f=new Frame("Client");
ta=new TextArea();
tf=new TextField();
Button send=new Button("發送");
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){
System.exit(0);
}
});
f.setSize(400,400);
f.setLocation(600,0);
f.setVisible(true);
}
public void createThread(){
MyClientReader reader=new MyClientReader(this);
reader.start();
}
public void close(){
try{
dis.close();
dos.close();
s.close();
}
catch(IOException e){ e.printStackTrace();}
}
public DataInputStream getDataInputStream(){ return dis;}
public DataOutputStream getDataOutputStream(){return dos;}
public TextArea getTextArea(){return ta;}
public TextField getTextField(){return tf;}
}
class MyClientListener implements ActionListener{
private Main client;
public MyClientListener(Main client){
this.client=client;
}
public void actionPerformed(ActionEvent e){
TextField tf=client.getTextField();
String info=tf.getText();
client.getTextArea().append("自己說:"+info+"\n");
try{
client.getDataOutputStream().writeUTF(info);
}
catch(IOException e1){e1.printStackTrace();}
if (info.equals("bye")){
client.close();
System.exit(0);
}
tf.setText("");
tf.requestFocus();
}
}
class MyClientReader extends Thread {
private Main client;
public MyClientReader(Main client){
this.client=client;
}
public void run(){
String info;
DataInputStream dis=client.getDataInputStream();
TextArea ta=client.getTextArea();
try{
while (true){
info=dis.readUTF();
ta.append("對方說:"+info+"\n");
if (info.equals("bye")){
client.close();
System.exit(0);
}
}
}
catch(IOException e){
e.printStackTrace();
}
}
}
伺服器端:
package serversocket;
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
public class Main {
private ServerSocket ss;
private Socket s;
private DataInputStream dis;
private DataOutputStream dos;
private TextArea ta;
private TextField tf;
public static void main(String[] args) {
Main m=new Main();
m.createUI();
m.connect();
m.createThread();
}
public void connect(){
try{ss=new ServerSocket(8888); s=ss.accept();
dos=new DataOutputStream(s.getOutputStream());
dis=new DataInputStream(s.getInputStream());}
catch(IOException e){ e.printStackTrace();}
}
public void createUI(){
Frame f=new Frame("Server");
ta=new TextArea();
tf=new TextField();
Button send=new Button("發送");
Panel p=new Panel();
p.setLayout(new BorderLayout());
p.add(tf,"Center");
p.add(send,"East");
f.add(ta,"Center");
f.add(p,"South");
MyServerListener listener=new MyServerListener(this);
send.addActionListener(listener);
tf.addActionListener(listener);
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
f.setSize(400,400);
f.setLocation(600,0);
f.setVisible(true);
}
public void createThread(){
MyServerReader reader=new MyServerReader(this);
reader.start();
}
public void close(){
try{
dis.close();
dos.close();
s.close();
ss.close();
}
catch(IOException e){ e.printStackTrace();}
}
public DataInputStream getDataInputStream(){ return dis;}
public DataOutputStream getDataOutputStream(){return dos;}
public TextArea getTextArea(){return ta;}
public TextField getTextField(){return tf;}
}
class MyServerListener implements ActionListener{
private Main client;
public MyServerListener(Main client){
this.client=client;
}
public void actionPerformed(ActionEvent e){
TextField tf=client.getTextField();
String info=tf.getText();
client.getTextArea().append("自己說:"+info+"\n");
try{
client.getDataOutputStream().writeUTF(info);
}
catch(IOException e1){e1.printStackTrace();}
if (info.equals("bye")){
client.close();
System.exit(0);
}
tf.setText("");
tf.requestFocus();
}
}
class MyServerReader extends Thread {
private Main client;
public MyServerReader(Main client){
this.client=client;
}
public void run(){
String info;
DataInputStream dis=client.getDataInputStream();
TextArea ta=client.getTextArea();
try{
while (true){
info=dis.readUTF();
ta.append("對方說:"+info+"\n");
if (info.equals("bye")){
client.close();
System.exit(0);
}
}
}
catch(IOException e){
e.printStackTrace();
}
}
}
要先運行伺服器端,再運行客戶端!
㈢ 2個Java聊天小程序
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;
class MyChatter extends JFrame {
private JLabel jLName = new JLabel();
private JTextField jTName = new JTextField();
private JLabel jLSendMss = new JLabel();
private JLabel jLReceiveMss = new JLabel();
private JButton jBSend = new JButton();
private JButton jBClear = new JButton();
private JScrollPane jScrollPane1 = new JScrollPane();
private JTextPane jTSendMss = new JTextPane();
private JScrollPane jScrollPane2 = new JScrollPane();
private JTextPane jTReceiveMss = new JTextPane();
//窗口適配器
private MyWindowAdapter mwa=null;
//通訊用成員變數
private byte[] receiveBuf=new byte[1000];
private byte[] sendBuf=null;
private DatagramSocket datagramServer=null;
private DatagramSocket datagramClient=null;
private DatagramPacket receivePacket=null;
private DatagramPacket sendPacket=null;
private static final int PORT=5000;
private InetAddress inetAddr=null;
private Server server=null;
private String machineName=null;
private String sendMss=null;
class Server extends Thread{
public Server(){
start();
}
public void run(){
while(true){
try{
//System.out.println(datagramServer);
datagramServer.receive(receivePacket);
displayMss();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
class MyWindowAdapter extends WindowAdapter{
public void windowClosing(WindowEvent e) {
close();
System.exit(0);
}
}
class MyKeyAdapter extends KeyAdapter{
public void keyPressed(KeyEvent e){
//System.out.println(e.getKeyCode());
if(e.isShiftDown()&&e.getKeyCode()==10){
sendReady();
}
}
}
private void sendReady(){
if(!checkMachineName()){
return;
}
if(!checkSendMss()){
return;
}
if(sendMss()){
JOptionPane.showMessageDialog(null,"發送消息成功!","提示",JOptionPane.ERROR_MESSAGE);
}
else{
JOptionPane.showMessageDialog(null,"發送消息失敗!","提示",JOptionPane.ERROR_MESSAGE);
}
}
private boolean sendMss(){
try{
sendPacket=toDatagram(sendMss,inetAddr,PORT);
datagramClient.send(sendPacket);
}
catch(Exception e){
return false;
}
return true;
}
private DatagramPacket toDatagram(String s,InetAddress destIA,int destPort){
//sendBuf=new byte[s.length()+1];
//s.getBytes(0,s.length(),sendBuf,0);
try{
sendBuf=s.getBytes("GB2312");
}
catch(Exception e){
}
return new DatagramPacket(sendBuf,sendBuf.length,destIA,destPort);
}
private boolean checkMachineName(){
machineName=jTName.getText();
if(machineName.length()==0){
JOptionPane.showMessageDialog(null,"請輸入機器名!","警告",JOptionPane.ERROR_MESSAGE);
return false;
}
try{
inetAddr=InetAddress.getByName(machineName);
}
catch(UnknownHostException e){
JOptionPane.showMessageDialog(null,"不能識別的機器名或者機器不存在!","警告",JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
private boolean checkSendMss(){
sendMss=jTSendMss.getText();
if(sendMss.length()==0){
JOptionPane.showMessageDialog(null,"要發送的消息不能為空!","警告",JOptionPane.ERROR_MESSAGE);
return false;
}
return true;
}
private void displayMss(){
String mss=null;
String tmp=jTReceiveMss.getText();
try{
mss=new String(receivePacket.getData(),0,receivePacket.getLength(),"GB2312");
}
catch(Exception e){
}
jTReceiveMss.setText(tmp+mss+"\n");
}
private void close(){
}
private void init() throws IOException{
mwa=new MyWindowAdapter();
datagramServer=new DatagramSocket(PORT);
datagramClient=new DatagramSocket();
receivePacket=new DatagramPacket(receiveBuf,receiveBuf.length);
jTSendMss.addKeyListener(new MyKeyAdapter());
server=new Server();
}
public MyChatter() throws HeadlessException {
try {
jbInit();
init();
}
catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws HeadlessException {
MyChatter myChatter1 = new MyChatter();
myChatter1.addWindowListener(myChatter1.mwa);
myChatter1.setSize(400,410);
myChatter1.setVisible(true);
}
private void jbInit() throws Exception {
jLName.setText("機器名或IP地址:");
jLName.setBounds(new Rectangle(15, 7, 108, 18));
this.getContentPane().setLayout(null);
jTName.setBounds(new Rectangle(13, 27, 368, 22));
jLSendMss.setText("發送消息:");
jLSendMss.setBounds(new Rectangle(12, 54, 92, 20));
jLReceiveMss.setText("接收消息:");
jLReceiveMss.setBounds(new Rectangle(12, 208, 86, 19));
jBSend.setBounds(new Rectangle(97, 178, 68, 19));
jBSend.setText("發送");
jBSend.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
jBSend_actionPerformed(e);
}
});
jBClear.setText("清空");
jBClear.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(ActionEvent e) {
jBClear_actionPerformed(e);
}
});
jBClear.setBounds(new Rectangle(224, 179, 68, 19));
this.setResizable(false);
this.setTitle("張輝的聊天程序");
jScrollPane1.setBounds(new Rectangle(13, 77, 368, 90));
jScrollPane2.setBounds(new Rectangle(13, 228, 368, 145));
jTReceiveMss.setEditable(false);
this.getContentPane().add(jLName, null);
this.getContentPane().add(jTName, null);
this.getContentPane().add(jLSendMss, null);
this.getContentPane().add(jLReceiveMss, null);
this.getContentPane().add(jBSend, null);
this.getContentPane().add(jBClear, null);
this.getContentPane().add(jScrollPane1, null);
this.getContentPane().add(jScrollPane2, null);
jScrollPane2.getViewport().add(jTReceiveMss, null);
jScrollPane1.getViewport().add(jTSendMss, null);
}
void jBClear_actionPerformed(ActionEvent e) {
jTSendMss.setText("");
}
void jBSend_actionPerformed(ActionEvent e) {
sendReady();
}
}
絕對能用,OK!給分!!!
㈣ java聊天小程序如何實現多人群聊功能
我家裡還有一個明天給你帶過來.你給個QQ呀什麼的聯系方式.
㈤ 想求一個java聊天小程序,使用圖形用戶界面和socket通訊 功能:可以實現兩個人私聊功能和多人聊天功能。
我只介紹思路:
使用websocket創建ws伺服器,nat123解析一個地址,分配一個埠給他用,發布到外網。
客戶端撥通地址 登陸 接入websocket服務,心跳機制要做好,上下線掉線更新列表,注冊存儲用戶信息,更新用戶列表。
客戶端可以發起群聊、私聊、收發文件、分享,甚至發送伺服器消息,然後反饋消息,響應遠程服務事件。
這就是一個聊天軟體所做的事情,我介紹websocket可以響應多平台,多端通信。
㈥ 誰可以給我提供一份Java小程序 例如 用Java編寫的日歷 留言薄 聊天小程序 等 一定要有源代碼哦
猜數字行不?代碼如下:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class GuessNumber {
static int trys, A, B;
static String r, t;
public static int[] MakeGuessNumber(){
Random r = new Random();
int guess[] = new int[4];
for(int i=0; i<4; i++){
guess[i] = r.nextInt(10);
for(int j=i-1; j>=0; j--){
if(guess[i]==guess[j]){
i--;
break;}
}
}
return guess;
}
public static String getRundom(){
int guess[]=MakeGuessNumber();
return ""+guess[0]+guess[1]+guess[2]+guess[3];
}
public static void messageDialog(Object o){
JOptionPane.showMessageDialog(null, o);
}
public static void guessNumber(){
r=getRundom();
//System.out.println(r);
JFrame jf=new JFrame();
JButton b1=new JButton("新游戲");
JLabel l1=new JLabel("輸入:");
final JTextField jtf=new JTextField(10);
JButton b2=new JButton("提交");
final JTextArea jta=new JTextArea(10,10);
jta.append(" "+"Guess"+" "+"Result"+"\n");
JScrollPane scrollPane=new JScrollPane(jta);
JPanel jp1=new JPanel();
jp1.add(l1);
jp1.add(jtf);
jp1.add(b2);
jf.add(b1,BorderLayout.NORTH);
jf.add(jp1,BorderLayout.CENTER);
jf.add(scrollPane,BorderLayout.SOUTH);
b1.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
trys=0;
A=0;
B=0;
jta.setText(" "+"Guess"+" "+"Result"+"\n");
jtf.setText("");
r=getRundom();
//System.out.println(r);
}
});
b2.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
t=jtf.getText();
A=0;
B=0;
if(t.length()!=4||t.substring(0, 1).equals(t.substring(1, 2))
||t.substring(0, 1).equals(t.substring(2, 3))
||t.substring(0, 1).equals(t.substring(3, 4))
||t.substring(1, 2).equals(t.substring(2, 3))
||t.substring(1, 2).equals(t.substring(3, 4))
||t.substring(2, 3).equals(t.substring(3, 4))
||!t.matches("[0-9]*"))
messageDialog("Wrong Input!");
else{
jtf.setText("");
trys++;
if(t.substring(0, 1).equals(r.substring(0, 1)))
A++;
if(t.substring(0, 1).equals(r.substring(1, 2)))
B++;
if(t.substring(0, 1).equals(r.substring(2, 3)))
B++;
if(t.substring(0, 1).equals(r.substring(3, 4)))
B++;
if(t.substring(1, 2).equals(r.substring(1, 2)))
A++;
if(t.substring(1, 2).equals(r.substring(0, 1)))
B++;
if(t.substring(1, 2).equals(r.substring(2, 3)))
B++;
if(t.substring(1, 2).equals(r.substring(3, 4)))
B++;
if(t.substring(2, 3).equals(r.substring(2, 3)))
A++;
if(t.substring(2, 3).equals(r.substring(0, 1)))
B++;
if(t.substring(2, 3).equals(r.substring(1, 2)))
B++;
if(t.substring(2, 3).equals(r.substring(3, 4)))
B++;
if(t.substring(3, 4).equals(r.substring(3, 4)))
A++;
if(t.substring(3, 4).equals(r.substring(0, 1)))
B++;
if(t.substring(3, 4).equals(r.substring(1, 2)))
B++;
if(t.substring(3, 4).equals(r.substring(2, 3)))
B++;
jta.append(trys+" "+t+" "+A+"A"+B+"B"+"\n");
if(A==4){
if(trys>=4)
messageDialog("You win after "+trys+" trys!");
else if(trys<=3)
messageDialog("You win after only "+trys+" trys!");
}
}
}
});
jf.setSize(300, 300);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[]){
guessNumber();
}
}
㈦ JAVA聊天小程序
汗,LZ真是牛,這可不是一個小程序,怎麼可能全部代碼貼出來,也沒工夫寫額,以前在學校我做過,我把我的思路給你好了,首先寫出服務端和客戶端,多線程實現收發,支持點對點聊天,如果這些LZ不會,那就先去看看基礎吧,在此基礎上,創建登錄用戶類,有用戶ID(String),昵稱和socket屬性,一個房間管理類,用來管理私聊,群聊或者2個以上人的聊天,有一個MAP屬性,以聊天者ID相加的值為建,以保存所有聊天者socket的List為值,其中群聊是MAP的默認屬性,登陸一個用戶,value就添加他socket,當用戶選擇一個人私聊,或者幾個人群聊時,MAP創建相應的映射,就這樣了,當時我是全部實現了,但在關閉socket時有些問題。
具體邏輯和其中BUG,自己調和寫吧,例如用ID相加為建有時會有問題。
㈧ 如何用java做一個聊天小程序 要求使用圖形用戶界面,可以實現一個聊天室中多人聊天,也可以兩人私聊,
openfire
smack
spark
搜索一下
實現起來比較簡單
㈨ 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();
}
}