Java基于Tcp/ip連接的多人交互聊天室
本文實(shí)例為大家分享了Java Socket編程實(shí)現(xiàn)多人交互聊天室的具體代碼,供大家參考,具體內(nèi)容如下
本項(xiàng)目由三個(gè).java文件(Client.java、Server.java、UI.java)和一個(gè).jpg圖片文件組成UI.java是負(fù)責(zé)界面的構(gòu)成文件。本聊天室的界面極其簡單。主要分為兩個(gè)界面:第一個(gè)是啟動(dòng)時(shí)需要登陸的界面如下:

輸入名字進(jìn)去以后就可以直接聊天


這個(gè)聊天室相當(dāng)于群聊,每一個(gè)登陸進(jìn)去的人發(fā)的信息,其他人都會(huì)收到。
使用指南:
1.運(yùn)行Server.java文件,保證服務(wù)端的開啟
2.運(yùn)行UI.java文件,界面登陸。每運(yùn)行一個(gè)UI文件并登陸進(jìn)去,就代表一個(gè)客戶進(jìn)了群聊中,可進(jìn)行對話。
程序簡單易懂,非常適合初學(xué)者練習(xí)網(wǎng)絡(luò)編程的知識(shí)。
Client.java
import java.net.*;
import java.io.*;
import java.util.*;
public class Client{
String name;
Socket s;
UI ui;
//構(gòu)造方法 ,把UI對象傳過來
public Client(UI ui){
this.ui = ui;
}
//從登陸界面獲得名字并傳去服務(wù)端
public void getName(String name){
try{
s = new Socket("127.0.0.1",3000);
Cli1 d = new Cli1(s,ui);
d.start();
this.name = name;
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(name);
}catch(Exception e){
e.printStackTrace();
}
}
//從聊天界面獲得要發(fā)送的內(nèi)容并經(jīng)服務(wù)器轉(zhuǎn)發(fā)給各個(gè)客戶端
public void say(String content){
try{
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
dos.writeUTF(content);
}catch(Exception e){
e.printStackTrace();
}
}
}
//輸入和輸出
class Cli1 extends Thread {
UI ui;
Socket s ;
public Cli1(Socket s,UI ui){
this.s = s;
this.ui=ui;
}
public void run(){
try{
while(true){
DataInputStream dis = new DataInputStream(s.getInputStream());
String content = dis.readUTF();
if(!content.equals("")&&content!=null){
System.out.println(content);
ui.say(content);
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
Server.java
import java.net.*;
import java.io.*;
import java.util.*;
public class Server{
static Socket s;
static Socket[] soc;
static String[] name;
static int k = 5,i =0,j;
public static void main(String[] args){
Server ser = new Server();
try{
ServerSocket ss = new ServerSocket(3000);
soc = new Socket[k];
name = new String[k];
while(true){
s = ss.accept();
soc[i]= s;
j=i;
i++;
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
DataInputStream dis = new DataInputStream(s.getInputStream());
name[j] = dis.readUTF();
System.out.println(name[j]+"已進(jìn)入群聊!");
dos.writeUTF("歡迎你,"+name[j]);
new Ser1().start();
}
}catch(ConnectException e){
System.out.println("連接異常?。?);
}catch(IOException e){
e.printStackTrace();
}
}
}
class Ser1 extends Thread{
public int j;
public void run(){
try{
DataInputStream read = new DataInputStream((Server.soc[Server.j]).getInputStream());
j=Server.j;
while(true){
String con = read.readUTF();
if(con!=null){
System.out.println("該線程j為"+j);
for(int i = 0;i<Server.soc.length;i++){
if((i!=j)&&(Server.soc[i]!=null)){
DataOutputStream dos = new DataOutputStream((Server.soc[i]).getOutputStream());
dos.writeUTF(Server.name[Server.j]+"發(fā)送于 "+(new Date()));
dos.writeUTF(con);
}
}
}else{break;}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
UI.java
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
public class UI{
//主方法
public static void main(String[] args){
UI ui = new UI();
ui.cli = new Client(ui);
ui.initFrame();
ui.showLogin();
}
Ser1 ser1 = new Ser1();
//初始化業(yè)務(wù)對象
public Client cli = null;
public void initCli(){
}
//初始化主窗口
public int width = 720;
public int height = 550;
public JFrame jFrame = null; //界面窗口
public JLayeredPane layeredPane = null; //層疊容器
public JPanel backLayer = null; //背景層
public JPanel frontLayer = null; //前景層
public CardLayout cardLayout = null; //前景層布局器
public void initFrame(){
jFrame = new JFrame("老友聚樂部");
layeredPane = new JLayeredPane();
layeredPane.setPreferredSize(new Dimension(width, height));
jFrame.add(layeredPane);
jFrame.setResizable(false);
jFrame.pack();
jFrame.setVisible(true);
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
backLayer = new JPanel();
((FlowLayout)backLayer.getLayout()).setHgap(0);
((FlowLayout)backLayer.getLayout()).setVgap(0);
backLayer.setSize(width,height);
backLayer.setLocation(0,0);
JLabel bg = new JLabel(new ImageIcon("12.jpg"));
backLayer.add(bg);
layeredPane.add(backLayer,new Integer(0));
frontLayer = new JPanel();
cardLayout = new CardLayout(0,0);
frontLayer.setLayout(cardLayout);
frontLayer.setOpaque(false);
frontLayer.setSize(width,height);
frontLayer.setLocation(0,0);
layeredPane.add(frontLayer,new Integer(1));
}
//登錄界面
public JPanel loginPane = null;
public JTextField loginCodeInput = null;
public JLabel loginTipsLabel = null;
public void showLogin(){
if(loginPane == null){
loginPane = new JPanel();
loginPane.setOpaque(false);
Box loginBox = Box.createVerticalBox();
loginBox.add(Box.createVerticalStrut(180));
JPanel welcome_panel = new JPanel();
welcome_panel.setOpaque(false);
JLabel welcome_label = new JLabel("老友俱樂部");
welcome_label.setForeground(Color.WHITE);
welcome_label.setFont(new Font("微軟雅黑",Font.PLAIN,30));
welcome_panel.add(welcome_label);
loginBox.add(welcome_panel);
loginBox.add(Box.createVerticalStrut(50));
JPanel code_panel = new JPanel();
code_panel.setOpaque(false);
JLabel code_label = new JLabel("姓名:");
code_label.setForeground(Color.WHITE);
code_label.setFont(new Font("微軟雅黑",Font.PLAIN,25));
code_panel.add(code_label);
loginCodeInput = new JTextField(10);
loginCodeInput.setFont(new Font("微軟雅黑", Font.PLAIN,25));
code_panel.add(loginCodeInput);
loginBox.add(code_panel);
loginBox.add(Box.createVerticalStrut(30));
JPanel btn_panel = new JPanel();
btn_panel.setOpaque(false);
JButton login_btn = new JButton("登 錄");
login_btn.setFont(new Font("微軟雅黑",Font.PLAIN,15));
btn_panel.add(login_btn);
JButton reset_btn = new JButton("重 置");
reset_btn.setFont(new Font("微軟雅黑",Font.PLAIN,15));
btn_panel.add(reset_btn);
loginBox.add(btn_panel);
loginBox.add(Box.createVerticalStrut(10));
JPanel tips_panel = new JPanel();
tips_panel.setOpaque(false);
loginTipsLabel = new JLabel("");
loginTipsLabel.setForeground(new Color(238,32,32));
loginTipsLabel.setFont(new Font("微軟雅黑",Font.PLAIN,20));
tips_panel.add(loginTipsLabel);
loginBox.add(tips_panel);
loginPane.add(loginBox);
frontLayer.add("loginPane",loginPane);
cardLayout.show(frontLayer,"loginPane");
frontLayer.validate();
loginCodeInput.requestFocus();
reset_btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
loginCodeInput.setText("");
loginTipsLabel.setText("");
loginCodeInput.requestFocus();
}
});
login_btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
String code_str = loginCodeInput.getText();
if("".equals(code_str)){
loginTipsLabel.setText("姓名不能為空!");
loginCodeInput.requestFocus();
}else{
cli.getName(code_str);
showTalk();
}
}
});
}else{
cardLayout.show(frontLayer,"loginPane");
loginCodeInput.setText("");
loginTipsLabel.setText("");
loginCodeInput.requestFocus();
}
}
//聊天主界面
public JPanel menuPane = null;
public JTextArea input = null;
public JTextArea talk = new JTextArea(25,70);
public void showTalk(){
menuPane = new JPanel();
menuPane.setOpaque(false);
menuPane.setLayout(new BorderLayout());
JPanel up = new JPanel();
Box tipsBox = Box.createVerticalBox();
menuPane.add(up,BorderLayout.NORTH); //北邊頂上
up.add(tipsBox);
JLabel tips_label = new JLabel("在線朋友");
tips_label.setForeground(Color.WHITE);
tips_label.setFont(new Font("微軟雅黑",Font.PLAIN,20));
tips_label.setAlignmentX(Component.LEFT_ALIGNMENT);
tipsBox.add(tips_label);
tipsBox.add(Box.createVerticalStrut(10));
JLabel upTxt = new JLabel(""); //接收在線朋友(需完善)
tipsBox.add(upTxt);
JPanel talk_panel = new JPanel();//中間聊天對話框
talk_panel.setOpaque(false);
menuPane.add(talk_panel,BorderLayout.WEST);
JScrollPane sp = new JScrollPane(talk);
talk_panel.add(talk);
Box inputBox = Box.createHorizontalBox(); //下邊輸入框
menuPane.add(inputBox,BorderLayout.SOUTH);
JPanel input_panel = new JPanel();
input_panel.setOpaque(false); //放置輸入框
input = new JTextArea(4,30);
input.setFont(new Font("微軟雅黑",Font.PLAIN,20));
input.setAlignmentX(Component.LEFT_ALIGNMENT);
input_panel.add(input);
inputBox.add(input_panel);
inputBox.add(Box.createHorizontalStrut(0));
JButton send_btn = new JButton("發(fā)送");
send_btn.setFont(new Font("微軟雅黑",Font.PLAIN,15));
inputBox.add(send_btn);
frontLayer.add("menuPane",menuPane);
cardLayout.show(frontLayer,"menuPane");
frontLayer.validate();
send_btn.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
String append = talk.getText();
String content = input.getText();
talk.setText(append+'\n'+content);
input.setText("");
cli.say(content);
}
});
}
public void say(String content){
if(talk!=null){
String append = talk.getText();
talk.setText(append+'\n'+content);
}
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
全面了解java基本類型和封裝類型的區(qū)別及應(yīng)用
下面小編就為大家?guī)硪黄媪私鈐ava基本類型和封裝類型的區(qū)別及應(yīng)用。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-09-09
基于SpringCloudGateway實(shí)現(xiàn)微服務(wù)網(wǎng)關(guān)的方式
Spring?Cloud?Gateway是Spring?官方基于Spring?5.0,Spring?Boot?2.0和Project?Reactor?等技術(shù)開發(fā)的網(wǎng)關(guān),旨在為微服務(wù)架構(gòu)提供一種簡單而有效的統(tǒng)一的API路由管理方式,對SpringCloudGateway實(shí)現(xiàn)微服務(wù)網(wǎng)關(guān)相關(guān)知識(shí)感興趣的朋友一起看看吧2021-12-12
完美解決gson將Integer默認(rèn)轉(zhuǎn)換成Double的問題
下面小編就為大家?guī)硪黄昝澜鉀Qgson將Integer默認(rèn)轉(zhuǎn)換成Double的問題。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-03-03
基于JSON實(shí)現(xiàn)傳輸byte數(shù)組過程解析
這篇文章主要介紹了基于JSON實(shí)現(xiàn)傳輸byte數(shù)組過程解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06
Kafka單節(jié)點(diǎn)偽分布式集群搭建實(shí)現(xiàn)過程詳解
這篇文章主要介紹了Kafka單節(jié)點(diǎn)偽分布式集群搭建實(shí)現(xiàn)過程詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11
idea sql的xml文件出現(xiàn)紅色警告符的處理方式
這篇文章主要介紹了idea sql的xml文件出現(xiàn)紅色警告符處理方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-04-04

