服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Java基于Tcp/ip连接的多人交互聊天室

Java基于Tcp/ip连接的多人交互聊天室

2021-05-19 14:11风吹山岗 Java教程

这篇文章主要为大家详细介绍了Java基于Tcp/ip连接的多人交互聊天室,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了java  socket编程实现多人交互聊天室的具体代码,供大家参考,具体内容如下

本项目由三个.java文件(client.java、server.java、ui.java)和一个.jpg图片文件组成ui.java是负责界面的构成文件。本聊天室的界面极其简单。主要分为两个界面:第一个是启动时需要登陆的界面如下:

Java基于Tcp/ip连接的多人交互聊天室

输入名字进去以后就可以直接聊天

Java基于Tcp/ip连接的多人交互聊天室 
Java基于Tcp/ip连接的多人交互聊天室 
Java基于Tcp/ip连接的多人交互聊天室

这个聊天室相当于群聊,每一个登陆进去的人发的信息,其他人都会收到。
使用指南:

1.运行server.java文件,保证服务端的开启
2.运行ui.java文件,界面登陆。每运行一个ui文件并登陆进去,就代表一个客户进了群聊中,可进行对话。

程序简单易懂,非常适合初学者练习网络编程的知识。

client.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import java.net.*;
import java.io.*;
import java.util.*;
 
public class client{
 
  string name;
  socket s;
  ui ui;
  //构造方法 ,把ui对象传过来
  public client(ui ui){
    this.ui = ui;
  }
 
  //从登陆界面获得名字并传去服务端
  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();
    }
  }
  //从聊天界面获得要发送的内容并经服务器转发给各个客户端
  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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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]+"已进入群聊!");
        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]+"发送于 "+(new date()));
            dos.writeutf(con);
          }
        }
 
 
      }else{break;}
    }
 
  }catch(exception e){
    e.printstacktrace();
  }
  }
 
}

ui.java

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
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();
 
  //初始化业务对象
  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("发送");
      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);
    }
 
  }
 
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持萬仟网。

原文链接:https://blog.csdn.net/linzammyy/article/details/51594445

延伸 · 阅读

精彩推荐