當前位置:首頁 » 編程語言 » java聊天代碼

java聊天代碼

發布時間: 2022-06-24 10:01:42

① 跪求java群聊天代碼

3459067873有

② JAVA點對點聊天代碼

給你一個做得很垃圾的Scoket的聊天的!
import java.io.InputStream;
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.util.Date;

class Server
{
public Server()
{
try
{
ServerSocket s=new ServerSocket(8888);
Socket ss=s.accept();
OutputStream out=ss.getOutputStream();
DataOutputStream dout=new DataOutputStream(out);
InputStream in=ss.getInputStream();
DataInputStream din=new DataInputStream(in);
System.out.print(din.readUTF()+"!");
dout.writeUTF("你已經連接到伺服器"+"\t"+"你的地址:"+ss.getInetAddress()+"\t"
+"你的鏈接埠:"+ss.getLocalPort()+"\n");
new ReadMessage(din).start();
new SendMessage(dout).start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
new Server();
}
}

//接受客戶端信息
class ReadMessage extends Thread
{
private DataInputStream din;

public ReadMessage(DataInputStream din)
{
this.din=din;
}

public void run()
{
String str;
try
{
while (true)
{
str=din.readUTF();
System.out.println(new Date().toLocaleString()+"客戶端說:"+str);
if (str.equals("bye"))
{
System.out.println("客戶端下線!");
break;
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

// 發出伺服器信息
class SendMessage extends Thread
{
private DataOutputStream dout;

public SendMessage(DataOutputStream dout)
{
this.dout=dout;
}

public void run()
{
InputStreamReader inr=new InputStreamReader(System.in);
BufferedReader buf=new BufferedReader(inr);
String str;
try
{
while(true)
{
str=buf.readLine();
dout.writeUTF(str);
if (str.equals("bye"))
{
System.out.println("伺服器退出!");
System.exit(1);
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

import java.io.InputStream;
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.net.Socket;
import java.io.IOException;
import java.util.Date;

class Client
{
public Client()
{
try
{
Socket s=new Socket("192.168.1.2",8888);
InputStream in=s.getInputStream();
DataInputStream din=new DataInputStream(in);
OutputStream out=s.getOutputStream();
DataOutputStream dout=new DataOutputStream(out);
dout.writeUTF("伺服器你好!我是客戶端");
System.out.println(din.readUTF());
new Thread(new SenderMessage(dout)).start();
new Thread(new ReaderMessage(din)).start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
new Client();
}
}

class ReaderMessage implements Runnable
{
private DataInputStream din;

public ReaderMessage(DataInputStream din)
{
this.din=din;
}
public void run()
{
String str;
try
{
while(true)
{
str=din.readUTF();
System.out.println(new Date().toLocaleString()+"伺服器說:"+str);
if (str.equals("bye"))
{
System.out.println("伺服器已經關閉,此程序自動退出!");
break;
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

class SenderMessage implements Runnable
{
private DataOutputStream dout;

public SenderMessage(DataOutputStream dout)
{
this.dout=dout;
}
public void run()
{
String str;
InputStreamReader inf=new InputStreamReader(System.in);
BufferedReader buf=new BufferedReader(inf);
try
{
while (true)
{
str=buf.readLine();
dout.writeUTF(str);
if (str.equals("bye"))
{
System.out.println("客戶端自己退出!");
System.exit(1);
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

遠程運行測試通過!

③ 急需一個java編程實現的簡單聊天窗口代碼

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
public class ClientDemo01 {
public static void main(String[] args){
JFrame f=new JFrame("AA");
JPanel p1=new JPanel();
JPanel p2=new JPanel();
JTextArea ta=new JTextArea(15,30);
ta.setEditable(false); //文本域只讀
JScrollPane sp=new JScrollPane(ta); //滾動窗格
JTextField tf=new JTextField(20);
JButton b=new JButton("發送");
p1.add(sp);
p2.add(tf);
p2.add(b);
f.add(p1,"Center");
f.add(p2,"South");
f.setBounds(300,300,360,300);
f.setVisible(true);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Socket socket=null;
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
try{
socket=new Socket("192.168.0.4",5000);

bis=new BufferedInputStream(socket.getInputStream());
bos=new BufferedOutputStream(socket.getOutputStream());
MyThread01 mt=new MyThread01(bis,ta);
mt.start();
}catch(Exception e){
e.printStackTrace();
}
b.addActionListener(new ButtonActionListener01(tf,ta,bos));
}
}
class ButtonActionListener01 implements ActionListener{
JTextField tf;
JTextArea ta;
BufferedOutputStream bos;
public ButtonActionListener01(JTextField tf,JTextArea ta,BufferedOutputStream bos){
this.tf=tf;
this.ta=ta;
this.bos=bos;
}
public void actionPerformed(ActionEvent e){
String message=tf.getText();
if(!message.equals("")){
tf.setText(""); //清空文本框
ta.append("AA:"+message+"\n"); //添加到文本域並換行
try{
bos.write(message.getBytes());
bos.flush();
}catch(Exception ex){
System.out.println("發送失敗");
}
}
}
}
class MyThread01 extends Thread{
BufferedInputStream bis;
JTextArea ta;
public MyThread01(BufferedInputStream bis,JTextArea ta){
this.bis=bis;
this.ta=ta;
}
public void run(){
try{
while(true){
byte[] b=new byte[100];
int length=bis.read(b);
String message=new String(b,0,length);
ta.append("BB:"+message+"\n");
}
}catch(Exception e){
e.printStackTrace();
}
}
} import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
public class ServerDemo01{
public static void main(String[] args){
JFrame f=new JFrame("BB");
JPanel p1=new JPanel();
JPanel p2=new JPanel();
JTextArea ta=new JTextArea(12,30); //文本域,第一個參數為行數,第二個參數為列數
ta.setEditable(false); //文本域只讀
JScrollPane sp=new JScrollPane(ta); //滾動窗格
JTextField tf=new JTextField(20);
JButton b=new JButton("發送");
p1.add(sp);
p2.add(tf);
p2.add(b);
f.add(p1,"Center");
f.add(p2,"South");
f.setBounds(300,300,360,300);
f.setVisible(true);
f.setResizable(false);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

ServerSocket server=null;
Socket socket=null;
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
try{
server=new ServerSocket(5000);
//ta.append("等待AA連接...\n");
socket=server.accept();
//ta.append("AA已連接\n");
bis=new BufferedInputStream(socket.getInputStream());
bos=new BufferedOutputStream(socket.getOutputStream());
MyThread1 mt=new MyThread1(bis,ta);
mt.start();
}catch(Exception e){
e.printStackTrace();
}
b.addActionListener(new ButtonActionListener1(tf,ta,bos));
}
}
class ButtonActionListener1 implements ActionListener{
JTextField tf;
JTextArea ta;
BufferedOutputStream bos;
public ButtonActionListener1(JTextField tf,JTextArea ta,BufferedOutputStream bos){
this.tf=tf;
this.ta=ta;
this.bos=bos;
}
public void actionPerformed(ActionEvent e){
String message=tf.getText(); //獲取文本框中的內容
if(!message.equals("")){
tf.setText(""); //清空文本框
ta.append("BB:"+message+"\n"); //添加到文本域並換行
try{
bos.write(message.getBytes());
bos.flush();
}catch(Exception ex){
System.out.println("發送失敗!");
}
}
}
}
class MyThread1 extends Thread{
BufferedInputStream bis;
JTextArea ta;
public MyThread1(BufferedInputStream bis,JTextArea ta){
this.bis=bis;
this.ta=ta;
}
public void run(){
try{
while(true){
byte[] b=new byte[100];
int length=bis.read(b);
String message=new String(b,0,length);
ta.append("AA:"+message+"\n");
}
}catch(Exception e){
e.printStackTrace();
}
}
}

④ 急求一個關於UDP的JAVA實現多人聊天源代碼

import java.io.InputStream;
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.io.IOException;
import java.util.Date;

class Server
{
public Server()
{
try
{
ServerSocket s=new ServerSocket(8888);
Socket ss=s.accept();
OutputStream out=ss.getOutputStream();
DataOutputStream dout=new DataOutputStream(out);
InputStream in=ss.getInputStream();
DataInputStream din=new DataInputStream(in);
System.out.print(din.readUTF()+"!");
dout.writeUTF("你已經連接到伺服器"+"\t"+"你的地址:"+ss.getInetAddress()+"\t"
+"你的鏈接埠:"+ss.getLocalPort()+"\n");
new ReadMessage(din).start();
new SendMessage(dout).start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
new Server();
}
}

//接受客戶端信息
class ReadMessage extends Thread
{
private DataInputStream din;

public ReadMessage(DataInputStream din)
{
this.din=din;
}

public void run()
{
String str;
try
{
while (true)
{
str=din.readUTF();
System.out.println(new Date().toLocaleString()+"客戶端說:"+str);
if (str.equals("bye"))
{
System.out.println("客戶端下線!");
break;
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

// 發出伺服器信息
class SendMessage extends Thread
{
private DataOutputStream dout;

public SendMessage(DataOutputStream dout)
{
this.dout=dout;
}

public void run()
{
InputStreamReader inr=new InputStreamReader(System.in);
BufferedReader buf=new BufferedReader(inr);
String str;
try
{
while(true)
{
str=buf.readLine();
dout.writeUTF(str);
if (str.equals("bye"))
{
System.out.println("伺服器退出!");
System.exit(1);
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

import java.io.InputStream;
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.io.BufferedReader;
import java.net.Socket;
import java.io.IOException;
import java.util.Date;

class Client
{
public Client()
{
try
{
Socket s=new Socket("192.168.1.2",8888);
InputStream in=s.getInputStream();
DataInputStream din=new DataInputStream(in);
OutputStream out=s.getOutputStream();
DataOutputStream dout=new DataOutputStream(out);
dout.writeUTF("伺服器你好!我是客戶端");
System.out.println(din.readUTF());
new Thread(new SenderMessage(dout)).start();
new Thread(new ReaderMessage(din)).start();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
new Client();
}
}

class ReaderMessage implements Runnable
{
private DataInputStream din;

public ReaderMessage(DataInputStream din)
{
this.din=din;
}
public void run()
{
String str;
try
{
while(true)
{
str=din.readUTF();
System.out.println(new Date().toLocaleString()+"伺服器說:"+str);
if (str.equals("bye"))
{
System.out.println("伺服器已經關閉,此程序自動退出!");
break;
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

class SenderMessage implements Runnable
{
private DataOutputStream dout;

public SenderMessage(DataOutputStream dout)
{
this.dout=dout;
}
public void run()
{
String str;
InputStreamReader inf=new InputStreamReader(System.in);
BufferedReader buf=new BufferedReader(inf);
try
{
while (true)
{
str=buf.readLine();
dout.writeUTF(str);
if (str.equals("bye"))
{
System.out.println("客戶端自己退出!");
System.exit(1);
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

⑤ 速求用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里編寫聊天軟體的圖像界面代碼怎麼寫

如果你問的是怎麼寫界面的代碼,那麼 如果不需要太復雜 這樣就可以:
JFrame frame = new JFrame(name);//窗口
JTextField jtf; // 文本條
JTextArea jta; //文本域。
frame.setSize(400, 300); //大小
jta = new JTextArea(); //文本域
jta.setEditable(false); //不可編輯
jtf = new JTextField();//文件條

如果你問的是整個程序的代碼 那就先把分加到100吧 而且就算100估計也沒人會來給你寫
因為很麻煩的

⑦ 急求一個JAVA編寫的區域網聊天代碼不要求很復雜。只要可以在兩台機子上簡單的對話就可以。

//以下引入包
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.applet.*;
public class regit extends JApplet implements ActionListener,ItemListener//介面
{
String s=null;
//對象的聲明
JLabel labelname,labelpass,labelsxe,labeladdress,labelmail,labelphone;//標簽
JTextField textname,textaddress,textmail,textphone;//文本框
JRadioButton r1,r2;//單選按紐
ButtonGroup bg;//組
JPasswordField textpass;//密碼域
JButton buttonregit,buttonreset;//注冊按紐 重寫按紐
JPanel p;//面板
String sex;//定義性別字元串

URL url;//統一資源定位
BufferedWriter out1,out2;//流
BufferedReader in;

//布局方式
GridBagLayout gbl;
GridBagConstraints gc;
AppletContext co;//介面

//初始化
public void init()
{
//new 對象
labelname=new JLabel("用 戶 名:");
labelpass=new JLabel("用戶密碼:");
labelsxe=new JLabel("性別:");
labeladdress=new JLabel("地址:");
labelmail=new JLabel("電子郵件:");
labelphone=new JLabel("聯系電話:");

textname=new JTextField(15); textname.setForeground(Color.red);
textname.setToolTipText("請在這輸入你的用戶名");
textaddress=new JTextField(15);textaddress.setForeground(Color.red);
textaddress.setToolTipText("請在這輸入你的地址");
textmail=new JTextField(15); textmail.setForeground(Color.red);
textmail.setToolTipText("請在這里輸入你的E-mail地址");
textphone=new JTextField(15); textphone.setForeground(Color.red);
textphone.setToolTipText("請在這輸入你的電話號碼");

r1=new JRadioButton("男"); r1.setBackground(new Color(47,177,210));//設置顏色
r2=new JRadioButton("女"); r2.setBackground(new Color(47,177,210));//設置顏色
bg=new ButtonGroup();
bg.add(r1);bg.add(r2);//加入組,實現單選

textpass=new JPasswordField(15);
textpass.setToolTipText("在這里輸入密碼");
textpass.setForeground(Color.red);

buttonregit=new JButton("注冊"); buttonregit.setBackground(new Color(47,177,210));//設置顏色
buttonregit.setToolTipText("點擊按紐完成注冊");
buttonreset=new JButton("填寫"); buttonreset.setBackground(new Color(47,177,210));//設置顏色
buttonreset.setToolTipText("點擊按紐刷新重寫");

gbl=new GridBagLayout(); ///////////////////////////////////////
gc=new GridBagConstraints(); //////採用GridBagLayout布局方式////////

p=new JPanel();
p.setLayout(gbl);
p.setBackground(new Color(47,177,210));

this.getContentPane().add(p);//加入面板

gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=2;
gbl.setConstraints(labelname,gc);
p.add(labelname);

gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=2;
gbl.setConstraints(textname,gc);
p.add(textname);

gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=4;
gbl.setConstraints(labelpass,gc);
p.add(labelpass);

gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=4;
gbl.setConstraints(textpass,gc);
p.add(textpass);

gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=6;
gbl.setConstraints(labelsxe,gc);
p.add(labelsxe);

gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=6;
gbl.setConstraints(r1,gc);
p.add(r1);

gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=5;
gc.gridy=6;
gbl.setConstraints(r2,gc);
p.add(r2);

gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=8;
gbl.setConstraints(labeladdress,gc);
p.add(labeladdress);

gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=8;
gbl.setConstraints(textaddress,gc);
p.add(textaddress);

gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=10;
gbl.setConstraints(labelmail,gc);
p.add(labelmail);

gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=10;
gbl.setConstraints(textmail,gc);
p.add(textmail);

gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=12;
gbl.setConstraints(labelphone,gc);
p.add(labelphone);

gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=12;
gbl.setConstraints(textphone,gc);
p.add(textphone);

gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=2;
gc.gridy=16;
gbl.setConstraints(buttonregit,gc);
p.add(buttonregit);

gc.anchor=GridBagConstraints.NORTHWEST;
gc.gridx=4;
gc.gridy=16;
gbl.setConstraints(buttonreset,gc);
p.add(buttonreset);

/////////////////////////////////////////////
co=this.getAppletContext();
/////////////////////////////////////////////
buttonregit.addActionListener(this);//按紐事件的監聽
buttonreset.addActionListener(this);//按紐事件的監聽
r1.addItemListener(this);//選擇事件的監聽
r2.addItemListener(this);//選擇事件的監聽
textphone.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
//注冊按紐事件
if(e.getSource()==buttonregit)
{
String s1=textname.getText(); ////////////////////
String s2=new String(textpass.getPassword());////////////////////
String s3=textaddress.getText(); // 定義字元串 //
String s4=textmail.getText(); ////////////////////
String s5=textphone.getText(); ////////////////////
//判斷注冊資料 信息 是否為空
if(s1.length()==0 || s2.length()==0 ||s3.length()==0 ||s4.length()==0 ||s5.length()==0)
{
int error=JOptionPane.INFORMATION_MESSAGE;
JOptionPane.showMessageDialog(null,"資料不能為空,請重新注冊!","【溫馨提示】",error);
return;//彈出對話框並返回
}

try//寫入到txt文件
{
in=new BufferedReader(new FileReader("d:\\迷離視線聊天室\\password.txt"));
}
catch(Exception ee){}
String ss=s1;
try
{
while((s=in.readLine())!=null)
{
if(s.startsWith(ss))
{
JOptionPane.showMessageDialog(null,"用戶名已經存在,請更換名字!");
textname.setText("");//設置為空,重新輸入
textpass.setText("");
textaddress.setText("");
textmail.setText("");
textphone.setText("");
return;
}
}
}
catch(Exception ee){}
///////////////////////////以上代碼判斷是否有同名

{
try
{
out1=new BufferedWriter(new FileWriter("d:\\迷離視線聊天室\\password.txt",true));
out2=new BufferedWriter(new FileWriter("d:\\迷離視線聊天室\\message.txt",true));
}//創建文件
catch(Exception ee)
{}

try
{
out1.write(s1+"#"+s2);//寫
out1.newLine();
out2.write("用戶名:"+s1);
out2.newLine();
out2.write("密碼:"+s2);
out2.newLine();
out2.write("性別:"+sex);
out2.newLine();
out2.write("地址:"+s3);
out2.newLine();
out2.write("電子郵件:"+s4);
out2.newLine();
out2.write("電話:"+s5);
out2.newLine();
out1.flush();
out2.flush();//清理緩沖
out1.close();
out2.close();
}
catch(Exception ee)
{}
JOptionPane.showMessageDialog(null,"注冊成功!");
try
{
String qss="http://localhost/chatroom/chatjiemian.htm";
url=new url(/qss);//連接上網址
co.showDocument(url);
}
catch(Exception exx)
{}
}

}
//////////////////////以下為回車事件
if(e.getSource()==textphone)
{
String s1=textname.getText(); ////////////////////
String s2=new String(textpass.getPassword());////////////////////
String s3=textaddress.getText(); // 定義字元串 //
String s4=textmail.getText(); ////////////////////
String s5=textphone.getText(); ////////////////////
//判斷注冊資料 信息 是否為空
if(s1.length()==0 || s2.length()==0 ||s3.length()==0 ||s4.length()==0 ||s5.length()==0)
{
int error=JOptionPane.INFORMATION_MESSAGE;
JOptionPane.showMessageDialog(null,"資料不能為空,請重新注冊!","【溫馨提示】",error);
return;//彈出對話框並返回
}

try//寫入到txt文件
{
in=new BufferedReader(new FileReader("d:\\迷離視線聊天室\\password.txt"));
}
catch(Exception ee){}
String ss=s1;
try
{
while((s=in.readLine())!=null)
{
if(s.startsWith(ss))
{
JOptionPane.showMessageDialog(null,"用戶名已經存在,請更換名字!");
textname.setText("");//設置為空,重新輸入
textpass.setText("");
textaddress.setText("");
textmail.setText("");
textphone.setText("");
return;
}
}
}
catch(Exception ee){}
///////////////////////////以上代碼判斷是否有同名

{
try
{
out1=new BufferedWriter(new FileWriter("d:\\迷離視線聊天室\\password.txt",true));
out2=new BufferedWriter(new FileWriter("d:\\迷離視線聊天室\\message.txt",true));
}//創建文件
catch(Exception ee)
{}

try
{
out1.write(s1+"#"+s2);//寫
out1.newLine();
out2.write("用戶名:"+s1+"密碼:"+s2+"性別:"+sex+"地址:"+s3+"電子郵件:"+s4+"電話:"+s5);//寫
out2.newLine();
out1.flush();
out2.flush();//清理緩沖
out1.close();
out2.close();
}
catch(Exception ee)
{}
JOptionPane.showMessageDialog(null,"注冊成功!");
try
{
String qss="http://localhost/chatroom/chatjiemian.htm";
url=new url(/qss);//連接上網址
co.showDocument(url);
}
catch(Exception exx)
{}
}

}
if(e.getSource()==buttonreset)//刷新重寫事件
{
textname.setText("");
textpass.setText("");
textaddress.setText("");
textmail.setText("");
textphone.setText("");
}

}
//////////////////////////////////////////
//
public void itemStateChanged(ItemEvent ex)
{
if(ex.getSource()==r1)
{
sex=new String("男");
}
else if(ex.getSource()==r2)
{
sex=new String("女");
}
}
}
參考資料:試試看,剛在網上找的

⑧ 你好,你有用java編寫的聊天室的代碼嗎,基於c/s架構的

服務端 用戶名 y 密碼 1 客戶端代碼在我的評論里,這敲不了那麼多字,沒辦法。

登陸實現類:class Login
package com.server;

import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

public class Login {
boolean f=false;//按登錄時設置的一個標志
private JFrame frame = new JFrame("Welcome To MLDN") ;
//設置窗體
private JButton submit = new JButton("登陸");//設置登錄按鈕
private JButton reset = new JButton("重置");//設置重置按鈕
private JLabel nameLab = new JLabel("伺服器:") ;//標簽實例化
private JLabel passLab = new JLabel("密 碼:"); //標簽實例化
private JLabel infoLab = new JLabel("伺服器登陸系統"); //標簽實例化
private JTextField nameText = new JTextField(10);//單行文本輸入條
private JPasswordField passText = new JPasswordField() ;//單行密碼文本輸入條
public Login(){//登錄窗口構造方法
Font fnt = new Font("Serief",Font.ITALIC + Font.BOLD,12); //設置字體
infoLab.setFont(fnt) ; // 設置標簽的顯示文字
submit.addActionListener(new ActionListener(){ //採用內部匿名類
public void actionPerformed(ActionEvent e){
if(e.getSource()==submit){ //判斷觸發器源是否是提交按鈕
String tname = nameText.getText() ; //得到輸入的用戶名
String tpass = new String(passText.getPassword()) ;//得到輸入的密碼,此時通過getPassageword()方法返回的是字元數組
LoginCheck log = new LoginCheck(tname,tpass) ;//實例化LoginCheck對象,傳入輸入的用戶名和密碼
if(log.validate()){//對用戶名和密碼進行驗證
try{ //線程異常處理try
Thread.sleep(2000); //2秒後打開聊天窗口
f=true; //登錄成功後的表示項為true
frame.dispose(); //關閉本窗口
}catch(Exception e1){//異常獲取
e1.printStackTrace();
}
}else{
infoLab.setText("登陸失敗,錯誤的用戶名或密碼!") ;//登錄失敗
}
}
}
});

reset.addActionListener(new ActionListener(){ //採用內部匿名類
public void actionPerformed(ActionEvent e){
if(e.getSource()==reset){ //判斷觸發器源是否是提交按鈕
nameText.setText(""); //設置文本框中的內容
passText.setText(""); //設置文本框中的內容
infoLab.setText("伺服器登陸系統"); //恢復標簽顯示
}
}
});
frame.addWindowListener(new WindowAdapter(){//加入窗口監聽
public void windowClosing(WindowEvent e){ }
}); // 加入事件
frame.setLayout(null); //使用絕對定位
nameLab.setBounds(5,5,60,20); //設置標簽的位置及大小
passLab.setBounds(5,30,60,20); //設置標簽的位置及大小
infoLab.setBounds(5,65,220,30); //設置標簽的位置及大小
nameText.setBounds(65,5,100,20); //設置文本域的位置及大小
passText.setBounds(65,30,100,20); //設置密碼域的位置及大小
submit.setBounds(165,5,60,20); //設置按鈕的位置及大小
reset.setBounds(165,30,60,20); //設置按鈕的位置及大小
frame.add(nameLab); //向窗體加入標簽
frame.add(passLab); //向窗體加入標簽
frame.add(infoLab); //向窗體加入標簽
frame.add(nameText); //向窗體加入文本框
frame.add(passText); //向窗體加入密碼框
frame.add(submit); //向窗體加入按鈕
frame.add(reset) ;//向窗體加入按鈕
frame.setSize(280,130); //設置窗體大小
frame.getContentPane().setBackground(Color.green) ;//設置窗體的背景顏色
frame.setLocation(300,200) ;//設置窗體在電腦桌面上的位置
frame.setVisible(true); //顯示窗口
while(f==false){ //當登錄失敗時,一直循環運行,
}
new MyServer();//顯示窗體頁面
}
}

驗證登陸實現類 class LoginCheck
package com.server;

public class LoginCheck {
private String name ;//用戶名
private String password ;//密碼
//構造方法
public LoginCheck(String name,String password){
this.name = name ;//傳遞用戶名
this.password = password ;//傳遞密碼
}
//驗證用戶名和密碼
public boolean validate(){
//驗證方法
if("y".equals(name)&&"1".equals(password)){ //判斷用戶名和密碼是否正確
return true; //返回true
}else{
return false ;//返回false
}
}
}

package com.server;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.DateFormat;
import java.util.Date;
import javax.swing.*;

聊天實現類 class MyServer
public class MyServer {
protected JLabel lab10;
// 全體變數,做傳遞的一個組件
String s = "已經成功連接";

// 初始字元串,在兩個聊天窗口鏈接成功時輸出,同時作為兩個窗口傳遞字元的一個變數
// 構造方法
public MyServer(){
try{//異常處理
JFrame frame=new JFrame("伺服器窗口");
//設置窗體
frame.setLayout(null);
//讓布局管理器為空,使用絕對定位
Font fnt=new Font("Serief",Font.PLAIN,40);//字體設置
Font fnt1=new Font("Serief",Font.PLAIN,20);//字體設置
//我的用戶名顯示
JLabel lab1=new JLabel("伺服器名:",JLabel.LEFT);
//標簽實例化,文本左對齊
lab1.setBounds(8, 10, 100, 20);
//設置組件位置及大小
frame.add(lab1);
//添加組件
JTextField text2=new JTextField(30); //單行文本輸入組件
text2.setBounds(150, 10, 200, 20);//設置組件位置及大小
text2.setEnabled(false);//文本條不可編輯
text2.setText("笑笑聊天室");//輸入內容
text2.setFont(fnt1);//設置字體
frame.add(text2);//添加組件
//伺服器IP顯示
JLabel lab2=new JLabel("當前伺服器IP:",JLabel.LEFT);
//標簽實例化,文本左對齊
lab2.setBounds(8, 45, 100, 20);//設置組件位置及大小
frame.add(lab2);//添加組件
JTextField text3=new JTextField(30);//單行文本輸入組件
text3.setBounds(150, 45, 200, 20);//設置組件位置及大小
text3.setEnabled(false);
//文本不可編輯
text3.setText("127.0.0.1");//輸入內容
text3.setFont(fnt1);//設置字體
frame.add(text3);
//添加組件
//伺服器埠顯示
JLabel lab3=new JLabel("當前伺服器埠:",JLabel.LEFT);
//標簽實例化,文本左對齊
lab3.setBounds(8, 80, 100, 20);//設置組件位置及大小
frame.add(lab3);//添加組件
JTextField text4=new JTextField(30);//單行文本輸入組件
text4.setBounds(150, 80, 200, 20);//設置組件位置及大小
text4.setEnabled(false);//文本不可編輯
text4.setText("8888");//輸入內容
text4.setFont(fnt1);//設置字體
frame.add(text4);//添加組件
//聊天記錄顯示
JLabel lab4=new JLabel("聊天記錄如下:",JLabel.LEFT);
//標簽實例化 文本左對齊
lab4.setBounds(8, 115, 100, 20);//設置組件位置及大小
frame.add(lab4);//添加組件
final JTextArea text1=new JTextArea();//多行文本輸入組件
text1.setEnabled(false);//文本不可編輯
text1.setLineWrap(true);//自動換行
JScrollPane scr=new JScrollPane(text1,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS); //設置滾動條,水平和垂直滾動條始終顯示
scr.setBounds(8, 150, 450, 350);//設置組件位置及大小
frame.add(scr);//添加組件
//聊天輸入窗口及確定
JLabel lab5=new JLabel("請輸入聊天內容:",JLabel.LEFT); //標簽實例化,文本左對齊
lab5.setBounds(8, 500, 100, 20);//設置組件位置及大小
frame.add(lab5);//添加組件
final JTextArea text5=new JTextArea();//多行文本輸入組件
text5.setLineWrap(true);//自動換行
JScrollPane scr2=new JScrollPane(text5,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);//設置滾動條,水平和垂直滾動條始終顯示
scr2.setBounds(150, 500, 300, 50);//設置組件位置及大小
frame.add(scr2);//添加組件
final JButton but=new JButton("確定");//設置確定按鈕
but.setFont(fnt);//添加字體設置
but.setBounds(480, 500, 200, 50);//設置組件位置及大小
but.addActionListener(
new ActionListener(){ //採用內部匿名類
public void actionPerformed(ActionEvent e){
if(e.getSource()==but){ //判斷觸發器源是否是提交按鈕
text1.append("笑笑: "+lab10.getText()+"\n ");//在聊天記錄上添加文本
text1.append(text5.getText()+"\n"); //將輸入的聊天內容輸出在聊天記錄上
s=text5.getText(); //得到聊天內容
text5.setText(""); // 將聊天窗口內容設置為空
}
}
});
frame.add(but);//添加組件
//當前時間顯示
JLabel lab7=new JLabel("時間顯示:",JLabel.LEFT);//標簽實例化,文本左對齊
lab7.setBounds(450, 20, 100, 20);//設置組件位置及大小
frame.add(lab7);//添加組件
DateFormat df=DateFormat.getDateTimeInstance();//取得系統時間
String df2= df.format(new Date()); //將時間轉換成字元串
JLabel lab8=new JLabel(df2,JLabel.LEFT);//標簽實例化,文本左對齊
lab8.setBounds(520, 20, 130, 20);//設置組件位置及大小
frame.add(lab8);//添加組件
lab10=lab8; //傳遞時間顯示,以便能在聊天記錄上顯示記錄時間
new Time(lab8); //使時間動態顯示
//用戶列表顯示
JLabel lab6=new JLabel("用戶列表:",JLabel.LEFT);//標簽實例化,文本左對齊
lab6.setBounds(500, 40, 100, 20);//設置組件位置及大小
frame.add(lab6);//添加組件
JTextArea text6=new JTextArea();//標簽實例化,文本左對齊
text6.setEnabled(false);//文本不可編輯
text6.setLineWrap(true);//自動換行
JScrollPane scr3=new JScrollPane(text6,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);//設置滾動條,水平和垂直滾動條始終顯示
scr3.setBounds(460, 70, 220, 420);//設置組件位置及大小
frame.add(scr3);//添加組件
//窗口的屬性
frame.setSize(700,600);//窗口大小
frame.getContentPane().setBackground(Color.pink);//窗口的背景顏色
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//關閉窗口時關閉程序
frame.setLocation(100,50);//在電腦桌面上出現的位置
frame.setVisible(true);//顯示窗口
//連個窗口連接
//建立Server Socket並等待連接請求
ServerSocket server =new ServerSocket(8889);
Socket socket=server.accept();
//連接建立,通過Socket獲取連接上的輸入/輸出流
BufferedReader in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
final PrintWriter out =new PrintWriter(socket.getOutputStream());
//先讀取Client發送的數據,然後從標准輸入讀取數據發送給Client當接收到bye時關閉連接
String s1="",s2="";
//標志字元串,作為傳遞字元串使用
//得到其他窗口傳遞的字元串,並判斷是否結束
while(!(s1=in.readLine()).equals("bye")){
text6.setText("可可在線"); //當連接成功是在用戶列表中 輸出用戶名字
if(!s1.equals("")){ //如果傳遞的字元串不為 空
text1.append("可可: "+lab10.getText()+"\n ");//在聊天記錄上添加文本
text1.append(s1+"\n"); //將輸入的聊天內容輸出在聊天記錄上
}
s2=s;//將在聊天窗口中得到的字元串傳遞給輸出字元串
for(;s2.equals("")||s2.equals(null);s2=s){//當傳遞的字元串為空時等待用戶輸入聊天內容

}
s="";//將在聊天窗口中得到的字元串設為空
if(!s2.equals("")&&!s2.equals(null)){// s2不為空時做
out.println(s2); //向其他窗口輸出字元串
}
out.flush();//輸出聊天內容
}
//關閉連接
in.close();
out.close();
socket.close();
server.close();
}catch(Exception e){

}
}
//main函數
public static void main(String args[]){
new Login();//登錄實現 } }
}

}

時間類 class Time
package com.server;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JLabel;
import javax.swing.Timer; //時間類
public class Time {
public Time(JLabel time){
//構造方法 this.setTimer(time);
//設置時間
}
public void setTimer(JLabel time){
//設置時間方法
final JLabel varTime = time;
//傳遞組件
Timer timeAction = new Timer(1000, new ActionListener() {
//時間監聽
public void actionPerformed(ActionEvent e) {
long timemillis = System.currentTimeMillis();//得到系統時間
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//轉換日期顯示格式
varTime.setText(df.format(new Date(timemillis)));//輸出得到的時間
}
});
timeAction.start(); //開啟線程
}
}

⑨ JAVA 聊天室伺服器端和客戶端完整代碼

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.util.*;
import java.io.*;

public class Server extends JFrame
{
JMenuBar mb = new JMenuBar();
JMenu m1 = new JMenu("文件");
JMenu m2 = new JMenu("幫助");
JMenuItem mi1 = new JMenuItem("連接");
JMenuItem mi2 = new JMenuItem("退出");
JLabel lab1 = new JLabel("用戶在線列表");
JLabel lab2 = new JLabel("消息:");
JTextArea ta = new JTextArea(9,30);
java.awt.List list = new java.awt.List(9);
JTextField tf = new JTextField(24);
JButton b = new JButton("發送");
JScrollPane sp = new JScrollPane();
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();

ServerSocket serverSocket;
Socket socket;
ArrayList array = new ArrayList();
int connect;

public Server()
{
super("聊天伺服器");
setJMenuBar(mb);
mb.add(m1);
mb.add(m2);
m1.add(mi1);
m1.addSeparator();
m1.add(mi2);
sp.getViewport().add(ta);
p1.setLayout(new BorderLayout());
p3.add(lab1);
p1.add(p3,BorderLayout.NORTH);
p1.add(list,BorderLayout.SOUTH);
p2.add(lab2);
p2.add(tf);
p2.add(b);
getContentPane().add(sp,BorderLayout.NORTH);
getContentPane().add(p1,BorderLayout.CENTER);
getContentPane().add(p2,BorderLayout.SOUTH);
pack();
//伺服器端界面居中顯示
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = this.getSize();
if(frameSize.width > screenSize.width)
{
frameSize.width = screenSize.width;
}
if(frameSize.height > screenSize.height)
{
frameSize.height = screenSize.height;
}
setLocation((screenSize.width - frameSize.width)/2,
(screenSize.height - frameSize.height)/2);
setSize(400,430);
setVisible(true);
setResizable(false);

mi1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if(serverSocket == null)
{
try
{
serverSocket = new ServerSocket(7000);
ta.append("系統提示:"+" 聊天伺服器"
+" 正在啟動......\n");
}
catch(IOException ex)
{
ta.append("系統提示:"+" 聊天伺服器"
+" 啟動失敗!\n");
}
}
else
{
ta.append("系統消息:"+" 聊天伺服器"
+" 已經啟動......\n");
}
//啟動監聽客戶端連接線程
Thread t = new Watch();
t.start();
}
});
mi2.addActionListener(new ServerListener());
b.addActionListener(new ServerListener());
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
closeAll();
System.exit(0);
}
});
}

class Watch extends Thread
{
public void run()
{
while(true)
{
if(array.size() <= 10)
{
try
{
socket = serverSocket.accept();
}
catch(IOException ex)
{
ta.append("系統消息: "+ex+"\n");
}
//創建客戶端線程,一個線程對應一個客戶端
Client c = new Client(socket);
array.add(c);
c.start();
}
else
{
ta.append("系統消息:"+" 聊天伺服器"
+" 已經超過最大連接數,請待會連接!\n");
}
}
}
}

class Client extends Thread
{
String name;
String ip;
String ipAddress;
Socket socket;
BufferedReader br;
PrintStream ps;

public Client(Socket s)
{
try
{
socket = s;
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
ps = new PrintStream(s.getOutputStream());
}
catch (IOException ex)
{
ta.append("系統消息: "+ex+"\n");
}
}

public void run()
{
String info;
try
{
while(true)
{
info = br.readLine();
if(info == null)
break;
StringTokenizer st = new StringTokenizer(info, ":");
String keyword = st.nextToken();

//處理客戶端傳來的信息
if (keyword.equals("CONNECT"))
{
name = st.nextToken();
ip = st.nextToken();
ipAddress = ip.substring(ip.indexOf("/")+1);
ta.append("系統消息: " + name + "/"
+ ipAddress +" 已經連接\n");
list.add(name + " " + ip
+" 已經登錄");
notifyChatRoom();
}
else if (keyword.equals("MSG"))
{
String broadcast = st.nextToken();
StringBuffer message = new StringBuffer("MSG:" +broadcast);
message.append(st.nextToken("\0"));
if (broadcast.equals("BROAD"))
{

熱點內容
光遇安卓國服信箱在哪裡 發布:2022-06-29 02:52:41 瀏覽:428
資料庫管理系統的工作 發布:2022-06-29 02:51:50 瀏覽:765
日本qq上傳頭像失敗 發布:2022-06-29 02:47:12 瀏覽:482
力度384控台編程視頻1 發布:2022-06-29 02:47:10 瀏覽:852
酷博linux 發布:2022-06-29 02:47:07 瀏覽:871
光遇安卓從哪個季節開始的有任務的 發布:2022-06-29 02:44:02 瀏覽:339
編程地牢 發布:2022-06-29 02:41:25 瀏覽:153
雲存儲結構模型是什麼 發布:2022-06-29 02:39:39 瀏覽:724
批量上傳js 發布:2022-06-29 02:38:17 瀏覽:396
行業b2b網站源碼 發布:2022-06-29 02:38:14 瀏覽:138