import java.io.InputStream;
讓客戶滿意是我們工作的目標(biāo),不斷超越客戶的期望值來自于我們對這個(gè)行業(yè)的熱愛。我們立志把好的技術(shù)通過有效、簡單的方式提供給客戶,將通過不懈努力成為客戶在信息化領(lǐng)域值得信任、有價(jià)值的長期合作伙伴,公司提供的服務(wù)項(xiàng)目有:域名申請、網(wǎng)絡(luò)空間、營銷軟件、網(wǎng)站建設(shè)、江門網(wǎng)站維護(hù)、網(wǎng)站推廣。
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.io.BufferedReader;
import java點(diǎn)虐 .ServerSocket;
import java點(diǎn)虐 .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("你已經(jīng)連接到服務(wù)器"+"\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();
}
}
}
// 發(fā)出服務(wù)器信息
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("服務(wù)器退出!");
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點(diǎn)虐 .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("服務(wù)器你好!我是客戶端");
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()+"服務(wù)器說:"+str);
if (str.equals("bye"))
{
System.out.println("服務(wù)器已經(jīng)關(guān)閉,此程序自動退出!");
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();
}
}
}
//以下引入包
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java點(diǎn)虐 .*;
import java.applet.*;
public class regit extends JApplet implements ActionListener,ItemListener//接口
{
String s=null;
//對象的聲明
JLabel labelname,labelpass,labelsxe,labeladdress,labelmail,labelphone;//標(biāo)簽
JTextField textname,textaddress,textmail,textphone;//文本框
JRadioButton r1,r2;//單選按紐
ButtonGroup bg;//組
JPasswordField textpass;//密碼域
JButton buttonregit,buttonreset;//注冊按紐 重寫按紐
JPanel p;//面板
String sex;//定義性別字符串
URL url;//統(tǒng)一資源定位
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("聯(lián)系電話:");
textname=new JTextField(15); textname.setForeground(Color.red);
textname.setToolTipText("請?jiān)谶@輸入你的用戶名");
textaddress=new JTextField(15);textaddress.setForeground(Color.red);
textaddress.setToolTipText("請?jiān)谶@輸入你的地址");
textmail=new JTextField(15); textmail.setForeground(Color.red);
textmail.setToolTipText("請?jiān)谶@里輸入你的E-mail地址");
textphone=new JTextField(15); textphone.setForeground(Color.red);
textphone.setToolTipText("請?jiān)谶@輸入你的電話號碼");
r1=new JRadioButton("男"); r1.setBackground(new Color(47,177,210));//設(shè)置顏色
r2=new JRadioButton("女"); r2.setBackground(new Color(47,177,210));//設(shè)置顏色
bg=new ButtonGroup();
bg.add(r1);bg.add(r2);//加入組,實(shí)現(xiàn)單選
textpass=new JPasswordField(15);
textpass.setToolTipText("在這里輸入密碼");
textpass.setForeground(Color.red);
buttonregit=new JButton("注冊"); buttonregit.setBackground(new Color(47,177,210));//設(shè)置顏色
buttonregit.setToolTipText("點(diǎn)擊按紐完成注冊");
buttonreset=new JButton("填寫"); buttonreset.setBackground(new Color(47,177,210));//設(shè)置顏色
buttonreset.setToolTipText("點(diǎn)擊按紐刷新重寫");
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);//按紐事件的監(jiān)聽
buttonreset.addActionListener(this);//按紐事件的監(jiān)聽
r1.addItemListener(this);//選擇事件的監(jiān)聽
r2.addItemListener(this);//選擇事件的監(jiān)聽
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,"用戶名已經(jīng)存在,請更換名字!");
textname.setText("");//設(shè)置為空,重新輸入
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));
}//創(chuàng)建文件
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="";
url=new url(/qss);//連接上網(wǎng)址
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,"用戶名已經(jīng)存在,請更換名字!");
textname.setText("");//設(shè)置為空,重新輸入
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));
}//創(chuàng)建文件
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="";
url=new url(/qss);//連接上網(wǎng)址
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("女");
}
}
}
參考資料:試試看,剛在網(wǎng)上找的
Java多人聊天可以使用Java的Socket編程實(shí)現(xiàn),主要的思路是:使用服務(wù)器來維護(hù)所有客戶端的連接,并將客戶端之間的聊天信息進(jìn)行轉(zhuǎn)發(fā)。
具體的實(shí)現(xiàn)步驟如下:
創(chuàng)建服務(wù)器端:使用ServerSocket類創(chuàng)建一個(gè)服務(wù)器端,并監(jiān)聽指定的端口,等待客戶端的連接。
創(chuàng)建客戶端:使用Socket類創(chuàng)建一個(gè)客戶端,并連接到服務(wù)器端。
實(shí)現(xiàn)聊天功能:客戶端和服務(wù)器端之間可以通過輸入和輸出流進(jìn)行通信,客戶端將聊天信息發(fā)送給服務(wù)器,服務(wù)器再將其轉(zhuǎn)發(fā)給其他客戶端。
處理異常:在實(shí)現(xiàn)聊天功能時(shí),需要注意處理可能出現(xiàn)的異常,例如連接異常、輸入輸出異常等等。
一個(gè)簡單的Java多人聊天程序的代碼框架如下:
服務(wù)器端:
import java.io.IOException;
import java點(diǎn)虐 .ServerSocket;
import java點(diǎn)虐 .Socket;
import java.util.ArrayList;
public class ChatServer {
private ServerSocket serverSocket;
private ArrayListClientHandler clients;
public ChatServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
clients = new ArrayListClientHandler();
System.out.println("服務(wù)器已啟動,等待客戶端連接...");
}
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點(diǎn)虐 .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();
}
}
}