❶ 求一個用java socket編寫的聊天室程序,能運行的附帶源碼,有客戶端和伺服器端
也不知道怎麼說怎麼用,我寫的代碼,很久了,用的是awt,感覺Java在應用程序上沒前景所以就沒在深入了……現在主攻J2ee,代碼給你,你自己感覺吧
服務端:
import java.io.*;
import java.net.*;
import java.util.*;
public class ChatServer {
boolean started = false;
ServerSocket ss = null;
List<Client> clients = new ArrayList<Client>();
public static void main(String[] args) {
new ChatServer().start();
}
public void start() {
try {
ss = new ServerSocket(8888);
started = true;
} catch (BindException e) {
System.out.println("埠使用中....");
System.out.println("請關掉相關程序並重新運行伺服器!");
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
try {
while(started) {
Socket s = ss.accept();
Client c = new Client(s);
System.out.println("a client connected!");
new Thread(c).start();
clients.add(c);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Client implements Runnable {
private Socket s;
private DataInputStream dis = null;
private DataOutputStream dos = null;
private boolean bConnected = false;
public Client(Socket s) {
this.s = s;
try {
dis = new DataInputStream(s.getInputStream());
dos = new DataOutputStream(s.getOutputStream());
bConnected = true;
} catch (IOException e) {
e.printStackTrace();
}
}
public void send(String str) {
try {
dos.writeUTF(str);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
while(bConnected) {
String str = dis.readUTF();
System.out.println(str);
for(int i=0; i<clients.size(); i++) {
Client c = clients.get(i);
c.send(str);
}
}
} catch (EOFException e) {
System.out.println("Client closed!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(dis != null) dis.close();
if(dos != null) dos.close();
if(s != null) {
s.close();
//s = null;
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
客戶端,開兩個就能聊了……
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class ChatClient extends Frame {
Socket s = null;
DataOutputStream dos = null;
DataInputStream dis = null;
private boolean bConnected = false;
TextField tfTxt = new TextField();
TextArea taContent = new TextArea();
Thread tRecv = new Thread(new RecvThread());
public static void main(String[] args) {
new ChatClient().launchFrame();
}
public void launchFrame() {
setLocation(400, 300);
this.setSize(300, 300);
add(tfTxt, BorderLayout.SOUTH);
add(taContent, BorderLayout.NORTH);
pack();
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent arg0) {
disconnect();
System.exit(0);
}
});
tfTxt.addActionListener(new TFListener());
setVisible(true);
connect();
tRecv.start();
}
public void connect() {
try {
s = new Socket("127.0.0.1", 8888);
dos = new DataOutputStream(s.getOutputStream());
dis = new DataInputStream(s.getInputStream());
System.out.println("connected!");
bConnected = true;
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public void disconnect() {
try {
dos.close();
dis.close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private class TFListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String str = tfTxt.getText().trim();
tfTxt.setText("");
try {
dos.writeUTF(str);
dos.flush();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
private class RecvThread implements Runnable {
public void run() {
try {
while(bConnected) {
String str = dis.readUTF();
taContent.setText(taContent.getText() + str + '\n');
}
} catch (SocketException e) {
System.out.println("�˳��ˣ�bye!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
❷ 提供一個由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聊天室 客戶端 和 伺服器 完整代碼
CS模式的QQ這是伺服器:ChatServer.javaimport java.net.*;
import java.io.*;
public class ChatServer
{
final static int thePort=8189;
ServerSocket theServer;
ChatHandler[] chatters;
int numbers=0;
public static void main(String args[])
{
ChatServer app=new ChatServer();
app.run();
}
public ChatServer()
{
try
{
theServer=new ServerSocket(thePort);
chatters=new ChatHandler[10];
}
catch(IOException io){}
}
public void run()
{
try
{
System.out.println("伺服器已經建立!");
while(numbers<10)
{
Socket theSocket=theServer.accept();
ChatHandler chatHandler=new ChatHandler(theSocket,this);
chatters[numbers]=chatHandler;
numbers++;
}
}catch(IOException io){}
}
public synchronized void removeConnectionList(ChatHandler c)
{
int index=0;
for(int i=0;i<=numbers-1;i++)
if(chatters[i]==c)index=i;
for(int i=index;i<numbers-1;i++)
chatters[i]=chatters[i+1];
chatters[numbers-1]=null;
numbers--;
}
public synchronized String returnUsernameList()
{
String line="";
for(int i=0;i<=numbers-1;i++)
line=line+chatters[i].user+":";
return line;
}
public void broadcastMessage(String line)
{
System.out.println("發布信息:"+line);
for(int i=0;i<=numbers-1;i++)
chatters[i].sendMessage(line);
}
}====================================================這是客戶端:ChatClient.javaimport java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
public class ChatClient extends Thread implements ActionListener
{
JTextField messageField,IDField,ipField,portField;
JTextArea message,users;
JButton connect,disconnect;
String user="";
String userList[]=new String[10];
Socket theSocket;
BufferedReader in;
PrintWriter out;
boolean connected=false;
Thread thread;
public static void main(String args[])
{
JFrame frame=new JFrame("聊天室");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ChatClient cc=new ChatClient();
JPanel content=cc.createComponents();
frame.getContentPane().add(content);
frame.setSize(550,310);
frame.setVisible(true);
}
public JPanel createComponents()
{
JPanel pane=new JPanel(new BorderLayout());
message=new JTextArea(10,35);
message.setEditable(false);
JPanel paneMsg=new JPanel();
paneMsg.setBorder(BorderFactory.createTitledBorder("聊天內容"));
paneMsg.add(message);
users=new JTextArea(10,10);
JPanel listPanel=new JPanel();
listPanel.setBorder(BorderFactory.createTitledBorder("在線用戶:"));
listPanel.add(users);
messageField=new JTextField(50);
IDField=new JTextField(5);
ipField=new JTextField("LocalHost");
portField=new JTextField("8189");
connect=new JButton("連 接");
disconnect=new JButton("斷 開");
disconnect.setEnabled(false);
JPanel buttonPanel=new JPanel();
buttonPanel.add(new Label("伺服器IP:"));
buttonPanel.add(ipField);
buttonPanel.add(new Label("埠:"));buttonPanel.add(portField);
buttonPanel.add(new Label("用戶名:"));
buttonPanel.add(IDField);
buttonPanel.add(connect);
buttonPanel.add(disconnect);
pane.add(messageField,"South");
pane.add(buttonPanel,"North");
pane.add(paneMsg,"Center");
pane.add(listPanel,"West");
connect.addActionListener(this);
disconnect.addActionListener(this);
messageField.addActionListener(this);
IDField.addActionListener(this);
ipField.addActionListener(this);
return pane;
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==connect){
user=IDField.getText();
String ip=ipField.getText();
int port =Integer.parseInt(portField.getText());
if(!user.equals("")&&connectToServer(ip,port,user))
{
disconnect.setEnabled(true);
connect.setEnabled(false);
}
}
if(e.getSource()==disconnect)disconnectFromServer();
if(e.getSource()==messageField)
if(theSocket!=null)
{
out.println("MESSAGE:"+messageField.getText());
messageField.setText("");
}
}
public void disconnectFromServer()
{
if(theSocket!=null)
{
try
{
connected=false;
out.println("LEAVE:"+user);
disconnect.setEnabled(false);
connect.setEnabled(true);
thread=null;
theSocket.close();
}catch(IOException io){}
theSocket=null;
message.setText("");
users.setText("");
}
}
public boolean connectToServer(String ip,int port,String ID)
{
if(theSocket!=null)
return false;
try
{
theSocket=new Socket(ip,port);
in=new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
out=new PrintWriter(new OutputStreamWriter(theSocket.getOutputStream()),true);
out.println("USER:"+user);
message.setText("");
connected=true;
thread=new Thread(this);
thread.start();
}catch(Exception e){return false;}
return true;
}
public void extractMessage(String line)
{
System.out.println(line);
Message messageline;
messageline=new Message(line);
if(messageline.isValid())
{
if(messageline.getType().equals("JOIN"))
{
user=messageline.getBody();
message.append(user+"進入了聊天室\n");
}
else if(messageline.getType().equals("LIST"))
updateList(messageline.getBody());
else if(messageline.getType().equals("MESSAGE"))
message.append(messageline.getBody()+"\n");
else if(messageline.getType().equals("REMOVE"))
message.append(messageline.getBody()+"離開了聊天室\n");
}
else
message.append("出現問題:"+line+"\n");
}
public void updateList(String line)
{
users.setText("");
String str=line;
for(int i=0;i<10;i++)
userList[i]="";
int index=str.indexOf(":");
int a=0;
while(index!=-1){
userList[a]=str.substring(0,index);
str=str.substring(index+1);
a++;
index=str.indexOf(":");
}
for(int i=0;i<10;i++)
users.append(userList[i]+"\n");
}
public void run(){
try{
String line="";
while(connected && line!=null){
line=in.readLine();
if(line!=null) extractMessage(line);
}
}catch(IOException e){}
}
} =======================================================import java.net.*;
import java.io.*;
class ChatHandler extends Thread{
Socket theSocket;
BufferedReader in;
PrintWriter out;
int thePort;
ChatServer parent;
String user="";
boolean disconnect=false;
public ChatHandler(Socket socket,ChatServer parent){
try{
theSocket=socket;
this.parent=parent;
in=new BufferedReader(new InputStreamReader(theSocket.getInputStream()));
out=new PrintWriter(new OutputStreamWriter(theSocket.getOutputStream()),true);
thePort=theSocket.getPort();
start();
}catch(IOException io){}
}
public void sendMessage(String line){
out.println(line);
}
public void setupUserName(String setname){
user=setname;
//System.out.print(user+"參加");
parent.broadcastMessage("JOIN:"+user);
}
public void extractMessage(String line){
Message messageline;
messageline = new Message(line);
if(messageline.isValid()){
if(messageline.getType().equals("USER")){
setupUserName(messageline.getBody());
parent.broadcastMessage("LIST:"+parent.returnUsernameList());
}
else if(messageline.getType().equals("MESSAGE")){
parent.broadcastMessage("MESSAGE:"+user+"說: "+messageline.getBody());
}
else if(messageline.getType().equals("LEAVE")){
String c=disconnectClient();
parent.broadcastMessage("REMOVE:"+c);
parent.broadcastMessage("LIST:"+parent.returnUsernameList());
}
}
else
sendMessage("命令不存在!");
}
public String disconnectClient(){
try{
in.close();
out.close();
theSocket.close();
parent.removeConnectionList(this);
disconnect=true;
}catch(Exception ex){}
return user;
}
public void run(){
String line,name;
boolean valid=false;
try{
while((line=in.readLine())!=null){
System.out.println("收到:"+line);
extractMessage(line);
}
}catch(IOException io){}
}
}
=========================================================
Message.javapublic class Message{
private String type;
private String body;
private boolean valid;
public Message(String messageLine){
valid=false;
type=body=null;
int pos=messageLine.indexOf(":");
if(pos>=0){
type=messageLine.substring(0,pos).toUpperCase();
body=messageLine.substring(pos+1);
valid=true;
}
}
public Message(String type,String body){
valid=true;
this.type=type;
this.body=body;
}
public String getType(){
return type;
}
public String getBody(){
return body;
}
public boolean isValid(){
return valid;
}
} ==================================================共有4個文件,先運行服務段端。。。 這是我以前學的時候寫過的!希望能幫的上你
❹ 速求用JAVA語言寫聊天室的源代碼
【.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多人聊天一般都是怎麼搭建的
Java多人聊天可以使用Java的Socket編程實現,主要的思路是:使用伺服器來維護所有客戶端的連接,並將客戶端之間的聊天信息進行轉發。巧稿歲
具體的實現步驟如下:
創建伺服器端:使用ServerSocket類創建一個伺服器端,並監聽指定的埠,等待客戶端的連接。
創建客戶端:使用Socket類創建一個客戶端,並連接到伺服器端。
實現聊天功能:客戶端和伺服器端之間可以通過輸入和輸出流進行通信,客戶端將聊天信息發送給伺服器,伺服器再將其轉發給其他客戶端。
處理異常:在實現聊天功能時,需要注意處理可能出現的異常,例如連接異常、孝睜輸入輸出異常等等。
一個簡單的Java多人聊天程序的代碼框架如下:
伺服器端:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class ChatServer {
private ServerSocket serverSocket;
private ArrayList<ClientHandler> clients;
public ChatServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
clients = new ArrayList<ClientHandler>();
System.out.println("伺服器已啟動,等敬差待客戶端連接...");
}
public void start() throws IOException {
while (true) {
Socket socket = serverSocket.accept();
ClientHandler client = new ClientHandler(socket, this);
clients.add(client);
client.start();
}
}
public void broadcast(String message) {
for (ClientHandler client : clients) {
client.sendMessage(message);
}
}
public void removeClient(ClientHandler client) {
clients.remove(client);
}
public static void main(String[] args) throws IOException {
ChatServer server = new ChatServer(12345);
server.start();
}
}
客戶端:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class ChatClient {
private Socket socket;
private BufferedReader reader;
private PrintWriter writer;
private String name;
public ChatClient(String serverAddress, int port, String name) throws IOException {
socket = new Socket(serverAddress, port);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream(), true);
this.name = name;
}
public void start() throws IOException {
System.out.println("歡迎來到聊天室!");
new Thread(new IncomingMessageHandler()).start();
new Thread(new OutgoingMessageHandler()).start();
}
private class IncomingMessageHandler implements Runnable {
@Override
public void run() {
try {
while (true) {
String message = reader.readLine();
if (message == null) {
break;
}
System.out.println(message);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
close();
}
}
}
private class OutgoingMessageHandler implements Runnable {
@Override
public void run() {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
try {
while (true) {
String message = reader.readLine();
if (message.equals("quit")) {
break;
}
writer.println(name + ": " + message);
}
} catch (IOException e) {
e.printStackTrace;
} finally {
close();
}
}
}
❻ java實現聊天室是怎麼做到的
Java 實現聊天室可以分為以下幾個步驟:
建立伺服器端
首先需要建立一個伺服器端,負責接收客戶端的連接請求並處理客戶端發送過來的消息。
建立客戶端
然後需要建立冊陸客戶端,客戶端通過正姿畢網路連接到伺服器端,並向伺服器端發送消息。
實現通信協議
為了實現聊天室功能,需要定義一個通信協議,規定客戶端和伺服器端之間的通信格式,例如消息的頭部和內容等。
實現多線程處理
聊天室通常會有多個用戶同時在線,因此需要使用多線程舉芹來處理多個客戶端的連接請求和消息傳遞。
實現GUI界面(可選)
為了方便用戶使用,可以實現一個GUI界面,讓用戶可以方便地發送和接收消息。
以下是一個簡單的 Java 聊天室的代碼示例:
java
Copy code
// 伺服器端代碼
public class Server {
public static void main(String[] args) {
try {
ServerSocket serverSocket = new ServerSocket(8888);
while (true) {
Socket socket = serverSocket.accept();
new Thread(new ServerThread(socket)).start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerThread implements Runnable {
private Socket socket;
private BufferedReader reader;
private PrintWriter writer;
public ServerThread(Socket socket) {
this.socket = socket;
try {
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
String msg;
while ((msg = reader.readLine()) != null) {
// 處理客戶端發送過來的消息
System.out.println("接收到消息:" + msg);
// 將消息發送給所有客戶端
for (Socket s : ServerThreadList.getList()) {
if (s != socket) {
PrintWriter w = new PrintWriter(s.getOutputStream());
w.println(msg);
w.flush();
}
}
}
// 關閉連接
socket.close();
ServerThreadList.removeThread(this);
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ServerThreadList {
private static List
list = new ArrayList<>();
public static void addThread(ServerThread thread) {
list.add(thread);
}
public static void removeThread(ServerThread thread) {
list.remove(thread);
}
public static List
getList() {
return list;
}
}
// 客戶端代碼
public class Client {
public static void main(String[] args) {
try {
Socket socket = new Socket("localhost", 8888);
new Thread(new ClientThread(socket)).start();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
PrintWriter writer = new PrintWriter(socket.getOutputStream());
while (true) {
String msg = reader.readLine();
writer.println(msg);
writer.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
class ClientThread implements Runnable {
private Socket socket;
private BufferedReader reader;
public ClientThread(Socket socket) {
this.socket = socket;
try {
reader
❼ 為java聊天室代碼加詳細注釋,並說明設計思路。好的加100分。
import java.io.*;
import java.net.*;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;//引入包。
public class ChatClient {
public static void main(String[] args) {
ChatClient cc = new ChatClient();
cc.receive();
}
JTextField jtf; // 文本條
JTextArea jta; //文本域。
Socket s; //客戶端
PrintWriter out; //輸出流
BufferedReader in; //輸入流
public ChatClient() {
JFrame frame = new JFrame("ChatClient");//窗口
frame.setSize(400, 300); //大小
jta = new JTextArea(); //文本域
jta.setEditable(false); //不可編輯
jtf = new JTextField();//文件條
jtf.addActionListener(new ActionListener() { //添加監聽。
public void actionPerformed(ActionEvent arg0) {
send(); //調用send()方法
}
});
frame.getContentPane().add(new JScrollPane(jta)); //添加滾動條
frame.getContentPane().add(jtf, "South"); //添加文本條
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //關閉窗口。
frame.setVisible(true); //可顯示的。
try {
s = new Socket("127.0.0.1", 9000); //連接服務端 socket("主機名",埠號);
in = new BufferedReader(new InputStreamReader(s.getInputStream())); //建立輸入流
out = new PrintWriter(s.getOutputStream());//輸出流
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void receive() { //接受服務端發來別的客戶端的信息。
while (true) {
try {
String text = in.readLine(); //讀一行
this.jta.append(text + "\n"); //jta 添加上讀入的。
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return;
}
}
}
public void send() { //發送消息
String text = this.jtf.getText(); //得到你輸入的消息
this.jtf.setText(""); //在文本域中顯示你輸入的消息。
out.println(text); //列印出。
out.flush(); //清空
}
}
Server端
import java.net.*;
import java.io.*;
import java.util.*;//引入包
public class ChatServer {
public static void main(String[] args) throws Exception {
ServerSocket ss = new ServerSocket(9000); //建立服務端,埠號為9000
List list = new ArrayList(); //創建個List集合。
while (true) {
Socket s = ss.accept(); //等待客戶端的請求。
list.add(s); //把每一個client都add到集合中去。
Thread t = new ServerThread(s, list); //線程。
t.start(); //啟動。
}
}
}
class ServerThread extends Thread {
Socket s;
List list;
BufferedReader in;
PrintWriter out;
public ServerThread(Socket s, List list) { //構造。傳入socket和list。
this.s = s;
this.list = list;
try {
in = new BufferedReader(new InputStreamReader(s.getInputStream())); //輸入流
out = new PrintWriter(s.getOutputStream()); //輸出流
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run() { //必須實現其run()方法。
while (true) {
try {
String str = in.readLine(); //得到client端的message。
if (str == null) //如果沒有消息就返回。
return;
Iterator it = list.iterator(); //遍歷list。
while (it.hasNext()) { //如果list有下一個
Socket socket = (Socket) (it.next()); //因為list中都是存的socket
PrintWriter o = new PrintWriter(socket.getOutputStream()); //輸出流
o.println(str); //輸出
o.flush(); //清空
}
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
return;
}
}
}
}