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();
}
}