導航:首頁 > 源碼編譯 > java聊天工具源碼

java聊天工具源碼

發布時間:2022-08-23 06:24:46

Ⅰ 怎麼樣用java做個聊天軟體

/**
* 基於UDP協議的聊天程序
*
* 2007.9.18
* */

//導入包
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.net.*;

public class Chat extends JFrame implements ActionListener
{
//廣播地址或者對方的地址
public static final String sendIP = "127.0.0.1";
//發送埠9527
public static final int sendPort = 8000;

JPanel p = new JPanel();
List lst = new List(); //消息顯示
JTextField txtIP = new JTextField(18); //填寫IP地址
JTextField txtMSG = new JTextField(20); //填寫發送消息
JLabel lblIP = new JLabel("IP地址:");
JLabel lblMSG = new JLabel("消息:");
JButton btnSend = new JButton("發送");

byte [] buf;

//定義DatagramSocket的對象必須進行異常處理
//發送和接收數據報包的套接字
DatagramSocket ds = null;

//=============構造函數=====================
public Chat()
{

CreateInterFace();
//注冊消息框監聽器
txtMSG.addActionListener(this);
btnSend.addActionListener(this);

try
{
//埠:9527
ds =new DatagramSocket(sendPort);
}
catch(Exception ex)
{

ex.printStackTrace();
}

//============接受消息============
//匿名類
new Thread(new Runnable()
{

public void run()
{
byte buf[] = new byte[1024];

//表示接受數據報包
while(true)
{
try
{
DatagramPacket dp = new DatagramPacket(buf,1024,InetAddress.getByName(txtIP.getText()),sendPort);
ds.receive(dp);
lst.add("【消息來自】◆" + dp.getAddress().getHostAddress() + "◆"+"【說】:" + new String (buf,0,dp.getLength()) /*+ dp.getPort()*/,0);
}
catch(Exception e)
{
if(ds.isClosed())
{
e.printStackTrace();
}
}
}
}
}).start();

//關閉窗體事件
this.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent w)
{
System.out.println("test");
int n=JOptionPane.showConfirmDialog(null,"是否要退出?","退出",JOptionPane.YES_NO_OPTION);
if(n==JOptionPane.YES_OPTION)
{
dispose();
System.exit(0);
ds.close();//關閉ds對象//關閉數據報套接字
}
}
});

}

//界面設計布局
public void CreateInterFace()
{
this.add(lst,BorderLayout.CENTER);
this.add(p,BorderLayout.SOUTH);
p.add(lblIP);
p.add(txtIP);
p.add(lblMSG);
p.add(txtMSG);
p.add(btnSend);
txtIP.setText(sendIP);
//背景顏色
lst.setBackground(Color.yellow);

//JAVA默認風格
this.setUndecorated(true);
this.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);

this.setSize(600,500);
this.setTitle("〓聊天室〓");
this.setResizable(false);//不能改變窗體大小
this.setLocationRelativeTo(null);//窗體居中
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
this.setVisible(true);
txtMSG.requestFocus();//消息框得到焦點
}

//===============================Main函數===============================

public static void main(String[]args)
{
new Chat();
}

//================================發送消息===============================
//消息框回車發送消息事件
public void actionPerformed(ActionEvent e)
{
//得到文本內容
buf = txtMSG.getText().getBytes();

//判斷消息框是否為空
if (txtMSG.getText().length()==0)
{
JOptionPane.showMessageDialog(null,"發送消息不能為空","提示",JOptionPane.WARNING_MESSAGE);
}
else{
try
{
InetAddress address = InetAddress.getByName(sendIP);
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort);
ds.send(dp);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
txtMSG.setText("");//清空消息框

//點發送按鈕發送消息事件
if(e.getSource()==btnSend)
{
buf = txtMSG.getText().getBytes();

try
{
DatagramPacket dp = new DatagramPacket(buf,buf.length,InetAddress.getByName(txtIP.getText()),sendPort);
}
catch(Exception ex)
{
ex.printStackTrace();
}

txtMSG.setText("");//清空消息框
txtMSG.requestFocus();
}

}

}

Ⅱ 求聊天軟體源代碼,java語言的

這東西需要伺服器啊(你要去申請?),我上次做了一半才發現就放棄了

Ⅲ 用JAVA編寫的簡單的聊天工具程序及解釋

控制台簡單聊天工具
服務端的代碼
import java.io.*;
import java.net.*;
import java.util.Scanner;

public class Server {

public static int PORT = 1007;
private ServerSocket server;
public Server() throws IOException {
server = new ServerSocket(PORT);
}
public static void main(String[] args) throws Exception {
System.out.println("--Server--");
Server server = new Server();
server.accept();
}

public void accept() throws IOException {
Socket client = server.accept();//等待客戶端的連接
getInfo(client.getInputStream());//啟動等待消息線程
toInfo(client.getOutputStream());//啟動發送消息線程
}

//等待客戶端發送消息
public void getInfo(InputStream in) throws IOException {
final Scanner sc = new Scanner(in);//獲取客戶端的輸入流
new Thread() {
@Override
public void run() {
while(true) {
if(sc.hasNextLine()) {//如果客戶端有發送消息過來
System.out.println("Client:" + sc.nextLine());//列印客戶端的消息
}
}
}
}.start();
}

//發送消息到客戶端
public void toInfo(OutputStream out) throws IOException {
final PrintWriter pw = new PrintWriter(out, true);//獲取客戶端的輸出流,自動清空緩存的內容
final Scanner sc = new Scanner(System.in);//獲取控制台的標准輸入流,從控制台輸入數據
new Thread() {
@Override
public void run() {
while(true) {
pw.println(sc.nextLine());//將輸入的數據發送給客戶端
}
}
}.start();
}
}

客戶端的代碼
import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client {

public static void main(String[] args) throws Exception, IOException {
System.out.println("--Client--");
Client client = new Client();
client.connection("localhost", Server.PORT);
}

public void connection(String host, int port) throws IOException {
Socket client = new Socket(host, port);
getInfo(client.getInputStream());
toInfo(client.getOutputStream());
}

public void getInfo(InputStream in) throws IOException {
final Scanner sc = new Scanner(in);
new Thread() {
@Override
public void run() {
while(true) {
if(sc.hasNextLine()) {
System.out.println("Server:" + sc.nextLine());
}
}
}
}.start();
}

public void toInfo(OutputStream out) throws IOException {
final PrintWriter pw = new PrintWriter(out, true);
final Scanner sc = new Scanner(System.in);
new Thread() {
@Override
public void run() {
while(true) {
pw.println(sc.nextLine());
}
}
}.start();
}
}

Ⅳ 提供一個由Java編寫的包括伺服器端和客戶端的聊天工具的原代碼

//聊天室的客戶端
import java.applet.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.awt.event.*;

public class ChatClient extends Applet{
protected boolean loggedIn;//登入狀態
protected Frame cp;//聊天室框架
protected static int PORTNUM=7777; //預設埠號7777
protected int port;//實際埠號
protected Socket sock;
protected BufferedReader is;//用於從sock讀取數據的BufferedReader
protected PrintWriter pw;//用於向sock寫入數據的PrintWriter
protected TextField tf;//用於輸入的TextField
protected TextArea ta;//用於顯示對話的TextArea
protected Button lib;//登入按鈕
protected Button lob;//登出的按鈕
final static String TITLE ="Chatroom applet>>>>>>>>>>>>>>>>>>>>>>>>";
protected String paintMessage;//發表的消息
public ChatParameter Chat;

public void init(){
paintMessage="正在生成聊天窗口";
repaint();
cp=new Frame(TITLE);
cp.setLayout(new BorderLayout());
String portNum=getParameter("port");//呢個參數勿太明
port=PORTNUM;
if (portNum!=null) //書上是portNum==null,十分有問題
port=Integer.parseInt(portNum);

//CGI

ta=new TextArea(14,80);
ta.setEditable(false);//read only attribute
ta.setFont(new Font("Monospaced",Font.PLAIN,11));
cp.add(BorderLayout.NORTH,ta);

Panel p=new Panel();
Button b;

//for login button
p.add(lib=new Button("Login"));
lib.setEnabled(true);
lib.requestFocus();
lib.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
login();
lib.setEnabled(false);
lob.setEnabled(true);
tf.requestFocus();//將鍵盤輸入鎖定再右邊的文本框中
}
});

//for logout button
p.add(lob=new Button ("Logout"));
lob.setEnabled(false);
lob.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
logout();
lib.setEnabled(true);
lob.setEnabled(false);
lib.requestFocus();
}
});

p.add(new Label ("輸入消息:"));
tf=new TextField(40);
tf.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(loggedIn){
//pw.println(Chat.CMD_BCAST+tf.getText());//Chat.CMD....是咩野來?
int j=tf.getText().indexOf(":");
if(j>0) pw.println(Chat.CMD_MESG+tf.getText());

else
pw.println(Chat.CMD_BCAST+tf.getText());
tf.setText("");//勿使用flush()?
}
}
});

p.add(tf);
cp.add(BorderLayout.SOUTH,p);

cp.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
//如果執行了setVisible或者dispose,關閉窗口
ChatClient.this.cp.setVisible(false);
ChatClient.this.cp.dispose();
logout();
}
});

cp.pack();//勿明白有咩用?
//將Frame cp放在中間
Dimension us=cp.getSize(),
them=Toolkit.getDefaultToolkit().getScreenSize();
int newX=(them.width-us.width)/2;
int newY=(them.height-us.height)/2;
cp.setLocation(newX,newY);
cp.setVisible(true);
paintMessage="Window should now be visible";
repaint();

}

//登錄聊天室
public void login(){
if(loggedIn) return;

try{
sock=new Socket(getCodeBase().getHost(),port);
is=new BufferedReader(new InputStreamReader(sock.getInputStream()));
pw=new PrintWriter(sock.getOutputStream(),true);
}catch(IOException e){
showStatus("Can't get socket: "+e);
cp.add(new Label("Can't get socket: "+e));
return;}

//構造並且啟動讀入器,從伺服器讀取數據,輸出到文本框中
//這里,長成一個線程來避免鎖住資源(lockups)
new Thread (new Runnable(){
public void run(){
String line;
try{
while(loggedIn &&((line=is.readLine())!=null))
ta.appendText(line+"\n");
}catch(IOException e){
showStatus("我的天啊,掉線了也!!!!");
return;
}
}
}).start();

//假定登錄(其實只是列印相關信息,並沒有真正登錄)
// pw.println(Chat.CMD_LOGIN+"AppletUser");
pw.println(Chat.CMD_LOGIN+"AppletUser");
loggedIn =true;

}

//模仿退出的代碼
public void logout(){
if(!loggedIn)
return;

loggedIn=false;
try{
if(sock!=null)
sock.close();
}catch(IOException ign){
// 異常處理哦
}

}

//沒有設置stop的方法,即使從瀏覽器跳到另外一個網頁的時候
//聊天程序還可以繼續運行

public void paint(Graphics g){
Dimension d=getSize();
int h=d.height;
int w=d.width;
g.fillRect(0,0,w,2);
g.setColor(Color.black);
g.drawString(paintMessage,10,(h/2)-5);

}

}

聊天室伺服器端
import java.net.*;
import java.io.*;
import java.util.*;

public class ChatServer{
//聊天室管理員ID
protected final static String CHATMASTER_ID="ChatMaster";
//系統信息的分隔符
protected final static String SEP=": ";
//伺服器的Socket
protected ServerSocket servSock;
//當前客戶端列表
protected ArrayList clients;
//調試標記
protected boolean DEBUG=false;
public ChatParameter Chat;

//主方法構造一個ChatServer,沒有返回值
public static void main(String[] argv){
System.out.println("Chat server0.1 starting>>>>>>>>>>>>>>>>");
ChatServer w=new ChatServer();
w.runServer();
System.out.println("***ERROR*** Chat server0.1 quitting");

}

//構造和運行一個聊天服務
ChatServer(){
Chat=new ChatParameter();
clients=new ArrayList();
try{
servSock=new ServerSocket(7777);//實有問題拉,不過可能是他自己定義既一個class.
System.out.println("Chat Server0.1 listening on port:"+7777);
}catch(Exception e){
log("IO Exception in ChatServer.<init>");
System.exit(0);
}
}

public void runServer(){
try{
while(true){
Socket us=servSock.accept();
String hostName=us.getInetAddress().getHostName();
System.out.println("Accpeted from "+hostName);
//一個處理的線程
ChatHandler cl=new ChatHandler(us,hostName);
synchronized(clients){
clients.add(cl);
cl.start();
if(clients.size()==1)
cl.send(CHATMASTER_ID,"Welcome!You are the first one here");
else{
cl.send(CHATMASTER_ID,"Welcome!You are the latest of"+
clients.size()+" users.");
}
}
}
}catch(Exception e){
log("IO Exception in runServer:"+e);
System.exit(0);
}
}

protected void log(String s){
System.out.println(s);
}

//處理會話的內部的類
protected class ChatHandler extends Thread {
//客戶端scoket
protected Socket clientSock;
//讀取socket的BufferedReader
protected BufferedReader is ;
//在socket 上發送信息行的PrintWriter
protected PrintWriter pw;
//客戶端出主機
protected String clientIP;
//句柄
protected String login;

public ChatHandler (Socket sock,String clnt)throws IOException {
clientSock=sock;
clientIP=clnt;
is=new BufferedReader(
new InputStreamReader(sock.getInputStream()));
pw=new PrintWriter (sock.getOutputStream(),true);

}

//每一個ChatHandler是一個線程,下面的是他的run()方法
//用於處理會話
public void run(){
String line;

try{
while((line=is.readLine())!=null){
char c=line.charAt(0);//我頂你老母啊 ,果只Chat.CMD咩xx冇定義 撲啊///!!!
line=line.substring(1);
switch(c){
//case Chat.CMD_LOGIN:
case 'l':
if(!Chat.isValidLoginName(line)){
send(CHATMASTER_ID,"LOGIN"+line+"invalid");
log("LOGIN INVALID from:"+clientIP);
continue;
}

login=line;
broadcast(CHATMASTER_ID,login+" joins us,for a total of"+
clients.size()+" users");
break;

// case Chat.CMD_MESG:
case 'm':
if(login==null){
send(CHATMASTER_ID,"please login first");
continue;
}

int where =line.indexOf(Chat.SEPARATOR);
String recip=line.substring(0,where);
String mesg=line.substring (where+1);
log("MESG: "+login+"--->"+recip+": "+mesg);
ChatHandler cl=lookup(recip);
if(cl==null)
psend(CHATMASTER_ID,recip+"not logged in.");
else
cl.psend(login,mesg);

break;

//case Chat.CMD_QUIT:
case 'q':
broadcast(CHATMASTER_ID,"Goodbye to "+login+"@"+clientIP);
close();
return;//ChatHandler結束

// case Chat.CMD_BCAST:
case 'b':
if(login!=null)
broadcast(login,line);
else
log("B<L FROM"+clientIP);
break;

default:
log("Unknow cmd"+c+"from"+login+"@"+clientIP);
}
}
}catch(IOException e){
log("IO Exception :"+e);
}finally{
//sock 結束,我們完成了
//還不能發送再見的消息
//得有簡單的基於命令的協議才行
System.out.println(login+SEP+"All Done");
synchronized(clients){
clients.remove(this);
if(clients.size()==0){
System.out.println(CHATMASTER_ID+SEP+
"I'm so lonely I could cry>>>>>");
}else if(clients.size()==1){
ChatHandler last=(ChatHandler)clients.get(0);
last.send(CHATMASTER_ID,"Hey,you are talking to yourself again");
}
else{
broadcast(CHATMASTER_ID,"There are now"+clients.size()+" users");
}
}
}
}

protected void close(){
if(clientSock==null){
log("close when not open");
return;
}
try{
clientSock.close();
clientSock=null;
}catch(IOException e){
log("Failure ring close to "+clientIP);
}
}

//發送一條消息給用戶
public void send(String sender,String mesg){
pw.println(sender+SEP+"*>"+mesg);
}

//發送私有的消息
protected void psend(String sender ,String msg){
send("<*"+sender+"*>",msg);
}

//發送一條消息給所有的用戶
public void broadcast (String sender,String mesg){
System.out.println("Broadcasting"+sender+SEP+mesg);
for(int i=0;i<clients.size();i++){
ChatHandler sib=(ChatHandler)clients.get(i);
if(DEBUG)
System.out.println("Sending to"+sib);
sib.send(sender,mesg);
}

if(DEBUG) System.out.println("Done broadcast");
}

protected ChatHandler lookup(String nick){
synchronized(clients){
for(int i=0;i<clients.size();i++){
ChatHandler cl=(ChatHandler)clients.get(i);
if(cl.login.equals(nick))
return cl;
}
}
return null;
}

//將ChatHandler對象轉換成一個字元串
public String toString(){
return "ChatHandler["+login+"]";
}

}

}

public class ChatParameter {
public static final char CMD_BCAST='b';
public static final char CMD_LOGIN='l';
public static final char CMD_MESG='m';
public static final char CMD_QUIT='q';
public static final char SEPARATOR=':';//?????
public static final int PORTNUM=7777;

public boolean isValidLoginName(String line){
if (line.equals("CHATMASTER_ID"))
return false;
return true;
}

public void main(String[] argv){
}
}
由於界面原因 所以比較亂 全部復制出去 重新整理一下就行了/

Ⅳ 給我提供一個Java編寫的聊天工具原代碼

//聊天室的客戶端
import java.applet.*;
import java.awt.*;
import java.io.*;
import java.net.*;
import java.awt.event.*;
public class ChatClient extends Applet{
protected boolean loggedIn;//登入狀態
protected Frame cp;//聊天室框架
protected static int PORTNUM=7777; //預設埠號7777
protected int port;//實際埠號
protected Socket sock;
protected BufferedReader is;//用於從sock讀取數據的BufferedReader
protected PrintWriter pw;//用於向sock寫入數據的PrintWriter
protected TextField tf;//用於輸入的TextField
protected TextArea ta;//用於顯示對話的TextArea
protected Button lib;//登入按鈕
protected Button lob;//登出的按鈕
final static String TITLE ="Chatroom applet>>>>>>>>>>>>>>>>>>>>>>>>";
protected String paintMessage;//發表的消息
public ChatParameter Chat;
public void init(){
paintMessage="正在生成聊天窗口";
repaint();
cp=new Frame(TITLE);
cp.setLayout(new BorderLayout());
String portNum=getParameter("port");//呢個參數勿太明
port=PORTNUM;
if (portNum!=null) //書上是portNum==null,十分有問題
port=Integer.parseInt(portNum);
//CGI
ta=new TextArea(14,80);
ta.setEditable(false);//read only attribute
ta.setFont(new Font("Monospaced",Font.PLAIN,11));
cp.add(BorderLayout.NORTH,ta);
Panel p=new Panel();
Button b;
//for login button
p.add(lib=new Button("Login"));
lib.setEnabled(true);
lib.requestFocus();
lib.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
login();
lib.setEnabled(false);
lob.setEnabled(true);
tf.requestFocus();//將鍵盤輸入鎖定再右邊的文本框中
}
});
//for logout button
p.add(lob=new Button ("Logout"));
lob.setEnabled(false);
lob.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
logout();
lib.setEnabled(true);
lob.setEnabled(false);
lib.requestFocus();
}
});
p.add(new Label ("輸入消息:"));
tf=new TextField(40);
tf.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
if(loggedIn){
//pw.println(Chat.CMD_BCAST+tf.getText());//Chat.CMD....是咩野來?
int j=tf.getText().indexOf(":");
if(j>0) pw.println(Chat.CMD_MESG+tf.getText());
else
pw.println(Chat.CMD_BCAST+tf.getText());
tf.setText("");//勿使用flush()?
}
}
});
p.add(tf);
cp.add(BorderLayout.SOUTH,p);
cp.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
//如果執行了setVisible或者dispose,關閉窗口
ChatClient.this.cp.setVisible(false);
ChatClient.this.cp.dispose();
logout();
}
});
cp.pack();//勿明白有咩用?
//將Frame cp放在中間
Dimension us=cp.getSize(),
them=Toolkit.getDefaultToolkit().getScreenSize();
int newX=(them.width-us.width)/2;
int newY=(them.height-us.height)/2;
cp.setLocation(newX,newY);
cp.setVisible(true);
paintMessage="Window should now be visible";
repaint();
}
//登錄聊天室
public void login(){
if(loggedIn) return;
try{
sock=new Socket(getCodeBase().getHost(),port);
is=new BufferedReader(new InputStreamReader(sock.getInputStream()));
pw=new PrintWriter(sock.getOutputStream(),true);
}catch(IOException e){
showStatus("Can't get socket: "+e);
cp.add(new Label("Can't get socket: "+e));
return;}
//構造並且啟動讀入器,從伺服器讀取數據,輸出到文本框中
//這里,長成一個線程來避免鎖住資源(lockups)
new Thread (new Runnable(){
public void run(){
String line;
try{
while(loggedIn &&((line=is.readLine())!=null))
ta.appendText(line+"\n");
}catch(IOException e){
showStatus("我的天啊,掉線了也!!!!");
return;
}
}
}).start();
//假定登錄(其實只是列印相關信息,並沒有真正登錄)
// pw.println(Chat.CMD_LOGIN+"AppletUser");
pw.println(Chat.CMD_LOGIN+"AppletUser");
loggedIn =true;

}
//模仿退出的代碼
public void logout(){
if(!loggedIn)
return;
loggedIn=false;
try{
if(sock!=null)
sock.close();
}catch(IOException ign){
// 異常處理哦
}
}
//沒有設置stop的方法,即使從瀏覽器跳到另外一個網頁的時候
//聊天程序還可以繼續運行
public void paint(Graphics g){
Dimension d=getSize();
int h=d.height;
int w=d.width;
g.fillRect(0,0,w,2);
g.setColor(Color.black);
g.drawString(paintMessage,10,(h/2)-5);
}
}

聊天室伺服器端
import java.net.*;
import java.io.*;
import java.util.*;

public class ChatServer{
//聊天室管理員ID
protected final static String CHATMASTER_ID="ChatMaster";
//系統信息的分隔符
protected final static String SEP=": ";
//伺服器的Socket
protected ServerSocket servSock;
//當前客戶端列表
protected ArrayList clients;
//調試標記
protected boolean DEBUG=false;
public ChatParameter Chat;

//主方法構造一個ChatServer,沒有返回值
public static void main(String[] argv){
System.out.println("Chat server0.1 starting>>>>>>>>>>>>>>>>");
ChatServer w=new ChatServer();
w.runServer();
System.out.println("***ERROR*** Chat server0.1 quitting");

}

//構造和運行一個聊天服務
ChatServer(){
Chat=new ChatParameter();
clients=new ArrayList();
try{
servSock=new ServerSocket(7777);//實有問題拉,不過可能是他自己定義既一個class.
System.out.println("Chat Server0.1 listening on port:"+7777);
}catch(Exception e){
log("IO Exception in ChatServer.<init>");
System.exit(0);
}
}

public void runServer(){
try{
while(true){
Socket us=servSock.accept();
String hostName=us.getInetAddress().getHostName();
System.out.println("Accpeted from "+hostName);
//一個處理的線程
ChatHandler cl=new ChatHandler(us,hostName);
synchronized(clients){
clients.add(cl);
cl.start();
if(clients.size()==1)
cl.send(CHATMASTER_ID,"Welcome!You are the first one here");
else{
cl.send(CHATMASTER_ID,"Welcome!You are the latest of"+
clients.size()+" users.");
}
}
}
}catch(Exception e){
log("IO Exception in runServer:"+e);
System.exit(0);
}
}

protected void log(String s){
System.out.println(s);
}

//處理會話的內部的類
protected class ChatHandler extends Thread {
//客戶端scoket
protected Socket clientSock;
//讀取socket的BufferedReader
protected BufferedReader is ;
//在socket 上發送信息行的PrintWriter
protected PrintWriter pw;
//客戶端出主機
protected String clientIP;
//句柄
protected String login;

public ChatHandler (Socket sock,String clnt)throws IOException {
clientSock=sock;
clientIP=clnt;
is=new BufferedReader(
new InputStreamReader(sock.getInputStream()));
pw=new PrintWriter (sock.getOutputStream(),true);

}

//每一個ChatHandler是一個線程,下面的是他的run()方法
//用於處理會話
public void run(){
String line;

try{
while((line=is.readLine())!=null){
char c=line.charAt(0);//我頂你老母啊 ,果只Chat.CMD咩xx冇定義 撲啊///!!!
line=line.substring(1);
switch(c){
//case Chat.CMD_LOGIN:
case 'l':
if(!Chat.isValidLoginName(line)){
send(CHATMASTER_ID,"LOGIN"+line+"invalid");
log("LOGIN INVALID from:"+clientIP);
continue;
}

login=line;
broadcast(CHATMASTER_ID,login+" joins us,for a total of"+
clients.size()+" users");
break;

// case Chat.CMD_MESG:
case 'm':
if(login==null){
send(CHATMASTER_ID,"please login first");
continue;
}

int where =line.indexOf(Chat.SEPARATOR);
String recip=line.substring(0,where);
String mesg=line.substring (where+1);
log("MESG: "+login+"--->"+recip+": "+mesg);
ChatHandler cl=lookup(recip);
if(cl==null)
psend(CHATMASTER_ID,recip+"not logged in.");
else
cl.psend(login,mesg);

break;

//case Chat.CMD_QUIT:
case 'q':
broadcast(CHATMASTER_ID,"Goodbye to "+login+"@"+clientIP);
close();
return;//ChatHandler結束

// case Chat.CMD_BCAST:
case 'b':
if(login!=null)
broadcast(login,line);
else
log("B<L FROM"+clientIP);
break;

default:
log("Unknow cmd"+c+"from"+login+"@"+clientIP);
}
}
}catch(IOException e){
log("IO Exception :"+e);
}finally{
//sock 結束,我們完成了
//還不能發送再見的消息
//得有簡單的基於命令的協議才行
System.out.println(login+SEP+"All Done");
synchronized(clients){
clients.remove(this);
if(clients.size()==0){
System.out.println(CHATMASTER_ID+SEP+
"I'm so lonely I could cry>>>>>");
}else if(clients.size()==1){
ChatHandler last=(ChatHandler)clients.get(0);
last.send(CHATMASTER_ID,"Hey,you are talking to yourself again");
}
else{
broadcast(CHATMASTER_ID,"There are now"+clients.size()+" users");
}
}
}
}
protected void close(){
if(clientSock==null){
log("close when not open");
return;
}
try{
clientSock.close();
clientSock=null;
}catch(IOException e){
log("Failure ring close to "+clientIP);
}
}
//發送一條消息給用戶
public void send(String sender,String mesg){
pw.println(sender+SEP+"*>"+mesg);
}
//發送私有的消息
protected void psend(String sender ,String msg){
send("<*"+sender+"*>",msg);
}
//發送一條消息給所有的用戶
public void broadcast (String sender,String mesg){
System.out.println("Broadcasting"+sender+SEP+mesg);
for(int i=0;i<clients.size();i++){
ChatHandler sib=(ChatHandler)clients.get(i);
if(DEBUG)
System.out.println("Sending to"+sib);
sib.send(sender,mesg);
}
if(DEBUG) System.out.println("Done broadcast");
}
protected ChatHandler lookup(String nick){
synchronized(clients){
for(int i=0;i<clients.size();i++){
ChatHandler cl=(ChatHandler)clients.get(i);
if(cl.login.equals(nick))
return cl;
}
}
return null;
}
//將ChatHandler對象轉換成一個字元串
public String toString(){
return "ChatHandler["+login+"]";
}
}
}

public class ChatParameter {
public static final char CMD_BCAST='b';
public static final char CMD_LOGIN='l';
public static final char CMD_MESG='m';
public static final char CMD_QUIT='q';
public static final char SEPARATOR=':';//?????
public static final int PORTNUM=7777;
public boolean isValidLoginName(String line){
if (line.equals("CHATMASTER_ID"))
return false;
return true;
}
public void main(String[] argv){
}
}

以上代碼由於界面限制的原因 可能有點兒亂
把它整個復制出去 重新整理修改一下就行了

Ⅵ 求javap2p聊天工具代碼

JAVA賀新年-自己動手做QQ(P2P聊天工具含源碼) - Dreamcode ~ ...
區塊鏈中的消息傳播離不p2p通信 java實現一個簡單的p2p通信demo工具: idea jdk1.8 maven1 : idea新建maven項...

Ⅶ 速求用JAVA語言寫聊天室的源代碼

【ClientSocketDemo.java 客戶端Java源代碼】

import java.net.*;
import java.io.*;
public class ClientSocketDemo
{
//聲明客戶端Socket對象socket
Socket socket = null;

//聲明客戶器端數據輸入輸出流
DataInputStream in;
DataOutputStream out;

//聲明字元串數組對象response,用於存儲從伺服器接收到的信息
String response[];

//執行過程中,沒有參數時的構造方法,本地伺服器在本地,取默認埠10745
public ClientSocketDemo()
{
try
{
//創建客戶端socket,伺服器地址取本地,埠號為10745
socket = new Socket("localhost",10745);

//創建客戶端數據輸入輸出流,用於對伺服器端發送或接收數據
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());

//獲取客戶端地址及埠號
String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());

//向伺服器發送數據
out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);

//從伺服器接收數據
response = new String[3];
for (int i = 0; i < response.length; i++)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}

//執行過程中,有一個參數時的構造方法,參數指定伺服器地址,取默認埠10745
public ClientSocketDemo(String hostname)
{
try
{
//創建客戶端socket,hostname參數指定伺服器地址,埠號為10745
socket = new Socket(hostname,10745);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());

String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());

out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);

response = new String[3];
for (int i = 0; i < response.length; i++)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}

//執行過程中,有兩個個參數時的構造方法,第一個參數hostname指定伺服器地址
//第一個參數serverPort指定伺服器埠號
public ClientSocketDemo(String hostname,String serverPort)
{
try
{
socket = new Socket(hostname,Integer.parseInt(serverPort));
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());

String ip = String.valueOf(socket.getLocalAddress());
String port = String.valueOf(socket.getLocalPort());

out.writeUTF("Hello Server.This connection is from client.");
out.writeUTF(ip);
out.writeUTF(port);

response = new String[3];
for (int i = 0; i < response.length; i++)
{
response[i] = in.readUTF();
System.out.println(response[i]);
}
}
catch(UnknownHostException e){e.printStackTrace();}
catch(IOException e){e.printStackTrace();}
}

public static void main(String[] args)
{
String comd[] = args;
if(comd.length == 0)
{
System.out.println("Use localhost(127.0.0.1) and default port");
ClientSocketDemo demo = new ClientSocketDemo();
}
else if(comd.length == 1)
{
System.out.println("Use default port");
ClientSocketDemo demo = new ClientSocketDemo(args[0]);
}
else if(comd.length == 2)
{
System.out.println("Hostname and port are named by user");
ClientSocketDemo demo = new ClientSocketDemo(args[0],args[1]);
}
else System.out.println("ERROR");
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

【ServerSocketDemo.java 伺服器端Java源代碼】

import java.net.*;
import java.io.*;
public class ServerSocketDemo
{
//聲明ServerSocket類對象
ServerSocket serverSocket;

//聲明並初始化伺服器端監聽埠號常量
public static final int PORT = 10745;

//聲明伺服器端數據輸入輸出流
DataInputStream in;
DataOutputStream out;

//聲明InetAddress類對象ip,用於獲取伺服器地址及埠號等信息
InetAddress ip = null;

//聲明字元串數組對象request,用於存儲從客戶端發送來的信息
String request[];

public ServerSocketDemo()
{
request = new String[3]; //初始化字元串數組
try
{
//獲取本地伺服器地址信息
ip = InetAddress.getLocalHost();

//以PORT為服務埠號,創建serverSocket對象以監聽該埠上的連接
serverSocket = new ServerSocket(PORT);

//創建Socket類的對象socket,用於保存連接到伺服器的客戶端socket對象
Socket socket = serverSocket.accept();
System.out.println("This is server:"+String.valueOf(ip)+PORT);

//創建伺服器端數據輸入輸出流,用於對客戶端接收或發送數據
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());

//接收客戶端發送來的數據信息,並顯示
request[0] = in.readUTF();
request[1] = in.readUTF();
request[2] = in.readUTF();
System.out.println("Received messages form client is:");
System.out.println(request[0]);
System.out.println(request[1]);
System.out.println(request[2]);

//向客戶端發送數據
out.writeUTF("Hello client!");
out.writeUTF("Your ip is:"+request[1]);
out.writeUTF("Your port is:"+request[2]);
}
catch(IOException e){e.printStackTrace();}
}
public static void main(String[] args)
{
ServerSocketDemo demo = new ServerSocketDemo();
}
}

Ⅷ 求用java編寫的聊天工具

這個只有源碼,沒有製作成軟體,在電腦可以直接運行,功能簡單,只有1,2項功能。如果想要完整的提交內容還是要花點錢的,畢竟這也是別人辛苦的腦力勞動。

Ⅸ 用Java編寫一個聊天工具

就50分啊,如果不是有現成的程序直接寫的話分是不是少了點哦

閱讀全文

與java聊天工具源碼相關的資料

熱點內容
組管理命令 瀏覽:979
海南高德司機端是什麼app 瀏覽:861
pid命令 瀏覽:888
一天一圖學會python可視化 瀏覽:309
魔獸編輯文本命令串 瀏覽:497
android中view繪制 瀏覽:798
安卓機內存刪除怎麼恢復 瀏覽:331
Qt環境的編譯軟體放到linux 瀏覽:214
聯創列印系統怎麼連接伺服器 瀏覽:935
杭州行政命令 瀏覽:160
如何查找伺服器日誌 瀏覽:801
加密的鑰匙扣怎麼寫 瀏覽:579
文件夾更新不了怎麼辦 瀏覽:475
壓縮機指示燈亮是什麼原因 瀏覽:956
什麼app訂酒店半價 瀏覽:767
中老年解壓神器 瀏覽:243
訊飛語音ttsandroid 瀏覽:468
腰椎壓縮性骨折術後能坐車嗎 瀏覽:507
python類裝飾器參數 瀏覽:350
均線pdf微盤 瀏覽:793