import java.io.InputStream;
成都創(chuàng)新互聯(lián)公司專注于金水網(wǎng)站建設(shè)服務(wù)及定制,我們擁有豐富的企業(yè)做網(wǎng)站經(jīng)驗。 熱誠為您提供金水營銷型網(wǎng)站建設(shè),金水網(wǎng)站制作、金水網(wǎng)頁設(shè)計、金水網(wǎng)站官網(wǎng)定制、微信小程序開發(fā)服務(wù),打造金水網(wǎng)絡(luò)公司原創(chuàng)品牌,更為您提供金水網(wǎng)站排名全網(wǎng)營銷落地服務(wù)。
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.DataOutputStream;
import java.io.BufferedReader;
import java點虐 .ServerSocket;
import java點虐 .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點虐 .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();
}
}
}
Java多人聊天可以使用Java的Socket編程實現(xiàn),主要的思路是:使用服務(wù)器來維護所有客戶端的連接,并將客戶端之間的聊天信息進行轉(zhuǎn)發(fā)。
具體的實現(xiàn)步驟如下:
創(chuàng)建服務(wù)器端:使用ServerSocket類創(chuàng)建一個服務(wù)器端,并監(jiān)聽指定的端口,等待客戶端的連接。
創(chuàng)建客戶端:使用Socket類創(chuàng)建一個客戶端,并連接到服務(wù)器端。
實現(xiàn)聊天功能:客戶端和服務(wù)器端之間可以通過輸入和輸出流進行通信,客戶端將聊天信息發(fā)送給服務(wù)器,服務(wù)器再將其轉(zhuǎn)發(fā)給其他客戶端。
處理異常:在實現(xiàn)聊天功能時,需要注意處理可能出現(xiàn)的異常,例如連接異常、輸入輸出異常等等。
一個簡單的Java多人聊天程序的代碼框架如下:
服務(wù)器端:
import java.io.IOException;
import java點虐 .ServerSocket;
import java點虐 .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點虐 .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();
}
}
}
先運行服務(wù)端?再運行客戶端???就能對話了
服務(wù)端
package?Liaotian;
import?java.awt.*;
import?java.awt.event.ActionEvent;
import?java.awt.event.ActionListener;
import?java.io.BufferedReader;
import?java.io.IOException;
import?java.io.InputStreamReader;
import?java.io.PrintWriter;
import?java點虐 .ServerSocket;
import?java點虐 .Socket;
import?java.text.SimpleDateFormat;
import?java.util.Date;
import?javax.swing.JPanel;
import?javax.swing.JScrollPane;
import?javax.swing.JTextArea;
public?class?fwjiemian?extends?Frame?implements?ActionListener{
JTextArea?lt;
TextField?sr;
Button?fs;
Panel?xia;
ServerSocket?ss;
Socket?s;
BufferedReader?br;
PrintWriter?pw;
BufferedReader?in;
public?fwjiemian(){
lt=new?JTextArea();
lt.setLineWrap(true);
sr=new?TextField();
fs=new?Button("發(fā)送");
xia=new?Panel(new?GridLayout(1,2));?
xia.add(sr);
xia.add(fs);
this.add(lt);
this.add(xia,BorderLayout.SOUTH);
this.setResizable(false);
this.setSize(400,?500);
this.setLocation(350,?100);
this.setTitle("服務(wù)器");
this.setVisible(true);
fs.addActionListener(this);
//創(chuàng)建客戶端+接受消息
try?{
lt.setFont(new???java.awt.Font("宋體",0,15));???
ss=new?ServerSocket(8888);
lt.append("服務(wù)器已啟動,等待客戶端接入..."+"\n"+"\n");
s=ss.accept();
lt.append("客戶端已接入..."+"\n"+"\n");
while(true){
//獲取時間
SimpleDateFormat?sm=new?SimpleDateFormat("HH:mm:ss");
System.out.println(sm.format(new?Date()));
//接受消息
br=new?BufferedReader(new?InputStreamReader(s.getInputStream()));
String?info=br.readLine();
lt.append("☆?客戶端:"+info+"????"+sm.format(new?Date())+"\n"+"\n");
}
}?catch?(Exception?e)?{
e.printStackTrace();
}
}
public?static?void?main(String[]?args)?{
new?fwjiemian();
}
@Override
public?void?actionPerformed(ActionEvent?e)?{
if(e.getSource()==fs){
try?{
//獲取時間
SimpleDateFormat?sm=new?SimpleDateFormat("HH:mm:ss");
System.out.println(sm.format(new?Date()));
//發(fā)送消息
String?infotokehu=sr.getText();
pw=new?PrintWriter(s.getOutputStream(),true);
pw.println(infotokehu);
lt.setFont(new???java.awt.Font("宋體",0,15));???
lt.append("★?服務(wù)器:"+infotokehu+"????"+sm.format(new?Date())+"\n"+"\n");
sr.setText("");
}?catch?(IOException?e1)?{
e1.printStackTrace();
}
}
}
}
客戶端
package?Liaotian;
import?java.awt.*;
import?java.awt.event.ActionEvent;
import?java.awt.event.ActionListener;
import?java.io.BufferedReader;
import?java.io.IOException;
import?java.io.InputStreamReader;
import?java.io.PrintWriter;
import?java點虐 .ServerSocket;
import?java點虐 .Socket;
import?java.text.SimpleDateFormat;
import?java.util.Date;
import?javax.swing.JScrollPane;
import?javax.swing.JTextArea;
public?class?khjiemian?extends?Frame?implements?ActionListener{
JTextArea?lt;
TextField?sr;
Button?fs;
Panel?xia;
Socket?s;
PrintWriter?pw;
BufferedReader?br;
BufferedReader?in;
public?khjiemian(){
lt=new?JTextArea();
lt.setLineWrap(true);?
sr=new?TextField();
fs=new?Button("發(fā)送");
xia=new?Panel(new?GridLayout(1,2));?
xia.add(sr);
xia.add(fs);
this.add(lt);
this.add(xia,BorderLayout.SOUTH);
this.setResizable(false);
this.setSize(400,?500);
this.setLocation(800,?100);
this.setTitle("服務(wù)器");
this.setVisible(true);
fs.addActionListener(this);
//創(chuàng)建客戶端+接受消息
try?{
lt.setFont(new???java.awt.Font("宋體",0,15));???
s=new?Socket("127.0.0.1",8888);
lt.append("客戶端已啟動,等待接入服務(wù)器..."+"\n"+"\n");
lt.append("已接入服務(wù)器..."+"\n"+"\n");
while(true){
//獲取時間
SimpleDateFormat?sm=new?SimpleDateFormat("HH:mm:ss");
System.out.println(sm.format(new?Date()));
//接受消息
br=new?BufferedReader(new?InputStreamReader(s.getInputStream()));
String?info=br.readLine();
lt.append("★?服務(wù)器:"+info+"????"+sm.format(new?Date())+"\n"+"\n");
}
}?catch?(Exception?e)?{
e.printStackTrace();
}?
}
public?static?void?main(String[]?args)?{
new?khjiemian();
}
public?void?actionPerformed(ActionEvent?w)?{
if(w.getSource()==fs){
try?{
//獲取時間
SimpleDateFormat?sm=new?SimpleDateFormat("HH:mm:ss");
System.out.println(sm.format(new?Date()));
//發(fā)消息
String?infotofuwu=sr.getText();
pw=new?PrintWriter(s.getOutputStream(),true);
pw.println(infotofuwu);
lt.setFont(new???java.awt.Font("宋體",0,15));???
lt.append("☆?客戶端:"+infotofuwu+"????"+sm.format(new?Date())+"\n"+"\n");
sr.setText("");
}
?catch?(Exception?e)?{
e.printStackTrace();
}?
}
}
}