導航:首頁 > 編程語言 > javachat

javachat

發布時間:2025-05-06 15:28:53

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

㈡ 微信是用什麼語言開發的

一般安卓手機的應用軟體目前都是以Java為主的程序語言開發的,包括微信。

許多的Android應用都是Java程序員開發者開發。雖然 Android運用了不同的JVM以及不同的封裝方式,但是代碼還是用Java語言所編寫。相當一部分的手機中都支持JAVA游戲,這就使很多非編程人員都認識了JAVA。

(2)javachat擴展閱讀

Java 語言是一門隨時代快速發展的計算機語言程序,其深刻展示了程序編寫的精髓,加上其簡明嚴謹的結構及簡潔的語法編寫為其將來的發展及維護提供了保障。由於提供了網路應用的支持和多媒體的存取,會推動Internet和企業網路的Web的應用 。

另外,為了保持Java的增長和推進Java社區的參與,Sun公司在Java One開發者大會上宣布開放Java核心源代碼,以鼓勵更多的人參與到Java社團活動中。來自Java社團和IBM等全球技術合作夥伴兩方面的支持,

Java技術在創新和社會進步上繼續發揮強有力的重要作用,並且隨著其程序編寫難度的降低使得更多專業人員將精力放置於Java語言的編寫與框架結構的設計中。

㈢ 給我提供一個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){
}
}

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

閱讀全文

與javachat相關的資料

熱點內容
php小數位數 瀏覽:383
pt100濕度感測器單片機 瀏覽:302
如何判斷伺服器運行慢 瀏覽:915
汽車貸款沒壓綠本需要解壓嘛 瀏覽:186
安卓如何實現單選 瀏覽:646
javanewfile編譯後找不到文件 瀏覽:851
盒馬app積分在哪裡看 瀏覽:504
怎麼把安卓轉到電腦 瀏覽:54
安卓怎麼查產生的圖片 瀏覽:26
看貓和老鼠用什麼app好 瀏覽:994
排列窗口命令圖片 瀏覽:201
製作公章怎麼加密 瀏覽:535
阿里雲伺服器秒殺價格表 瀏覽:109
空調壓縮機過濾器堵塞 瀏覽:909
編譯器和感測器 瀏覽:424
全什麼配音app 瀏覽:113
新氧app是干什麼的 瀏覽:374
什麼app可以免費下載小說 瀏覽:63
pgp桌面加密 瀏覽:97
java多線程編程視頻 瀏覽:662