[Java小程序]聊天室——Socket和ServerSocket的使用
这段小代码是因为担任Java助教给刚学习Java的本科大二的小学弟小学妹们指导,他们的实验作业就是编写一个Java聊天室客户端和服务器,为了避免出纰漏,自己事先写了一下。

客户端Ui代码:
package com.CS; import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField; public class Client_UI extends JFrame{
public JButton Connect; //创建连接按钮;
public JButton Say; //创建发送按钮;
public JPanel Panel; //创建一个用于存放所有组件的容器;
public JPanel Panel_up; //创建一个用于存放界面最上面各个组件的容器;
public JPanel Panel_down; //创建一个用于存放界面最下面各个组件的容器;
public JTextField Server_IP; //用于写IP地址的组件;
public JTextField Server_Port; //用于写端口号的组件;
public JTextField Say_Send; //用于写要发送的文字的内容的组件;
public JTextArea Text_Show; //用于显示相关信息的组件; public Client_Thread Server; //创建一个客户端线程; public Client_UI(){
Connect=new JButton("Connect");
Say=new JButton("Say");
Server_IP=new JTextField(10);
Server_Port=new JTextField(5);
Say_Send=new JTextField(25); Text_Show=new JTextArea();
JScrollPane ScrollPane=new JScrollPane(); //使之可以滚动,且设置滚动一直存在;
ScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
ScrollPane.setViewportView(Text_Show); Panel_up=new JPanel();
// Panel_up.setLayout(new GridLayout(1,5));
// Panel_up.setLayout(new FlowLayout(FlowLayout.LEFT));
Panel_up.setLayout(new GridBagLayout()); //布局方法,调试得出该布局方法最合理;
Panel_up.add(new JLabel("Server IP"));
Panel_up.add(Server_IP);
Panel_up.add(new JLabel("Server Port"));
Panel_up.add(Server_Port);
Panel_up.add(Connect); Panel_down=new JPanel();
// Panel_down.setLayout(new GridLayout(1,3));
Panel_down.setLayout(new FlowLayout(FlowLayout.LEFT)); //布局方法,调试得知,从左边最先开始存放组件。
Panel_down.add(new JLabel("Say"));
Panel_down.add(Say_Send);
Panel_down.add(Say); Panel=new JPanel();
Panel.setLayout(new BorderLayout());
Panel.add(Panel_up, BorderLayout.NORTH);
Panel.add(ScrollPane);
Panel.add(Panel_down,BorderLayout.SOUTH); this.setTitle("客户端");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400, 300);
this.setLocation(600, 200);
this.add(Panel);
this.setVisible(true); //对connect按钮增加监听;
Connect.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
Server=new Client_Thread(Client_UI.this);
}
}); //对Say按钮增加监听;
Say.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
Server.SendMessage(Say_Send.getText());
Say_Send.setText("");
}
});
} public static void main(String args[]){
Client_UI clientui=new Client_UI();
} }
客户端线程代码:
package com.CS; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
//import java.io.PrintWriter;
import java.net.Socket; public class Client_Thread extends Thread {
Client_UI UI;
Socket client_socket;
BufferedReader Read;
PrintStream Write; public Client_Thread(Client_UI ui){
this.UI=ui;
String IP=UI.Server_IP.getText().trim(); //获取IP地址;
int Port=Integer.parseInt(UI.Server_Port.getText().trim()); //获取端口号,并将其转换成int型;
try {
client_socket=new Socket(IP,Port); //设置连接服务器的IP地址和端口号;
Println("客户端连接服务器成功!");
Read=new BufferedReader(new InputStreamReader(client_socket.getInputStream()));
Write=new PrintStream(client_socket.getOutputStream());
} catch (IOException e) {
Println("客户端连接服务器失败!");
e.printStackTrace();
} new Thread(new Runnable(){
@Override
public void run() {
String message="";
while(true){
try {
message=Read.readLine();
} catch (IOException e) {
Println("连接服务器中断!");
e.printStackTrace();
break;
}
if(message!=null&&message.trim()!=""){
Println(message);
}
}
}
}).start();
} public void Println(String s){
if(s!=null){
this.UI.Text_Show.setText(this.UI.Text_Show.getText()+s+"\n");
System.out.println(s + "\n");
}
} public void SendMessage(String text){
try{
Write.println(text);
}catch(Exception e){
Println(e.toString());
}
} }
服务器UI代码:
package com.Server; import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.net.Socket;
import java.util.List;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener; import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField; public class Server_UI extends JFrame{
public JButton Start;
public JButton Say;
public JTextField Port_Msg;
public JTextField Say_Msg;
public JPanel Panel_up;
public JPanel Panel;
public JPanel Panel_down;
public JTextArea Text_show;
public Server server;
public List<Socket> clients; //保存服务器接收到的客户端; public Server_UI(){
Start=new JButton("Start");
Say=new JButton("Say"); Port_Msg=new JTextField(25);
Say_Msg=new JTextField(25); Text_show=new JTextArea();
JScrollPane ScrollPane=new JScrollPane();
ScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
ScrollPane.setViewportView(Text_show); Panel_up=new JPanel();
Panel_up.setLayout(new FlowLayout());
Panel_up.add(new JLabel("Port"));
Panel_up.add(Port_Msg);
Panel_up.add(Start); Panel_down=new JPanel();
Panel_down.setLayout(new FlowLayout());
Panel_down.add(new JLabel("Say"));
Panel_down.add(Say_Msg);
Panel_down.add(Say); Panel=new JPanel();
Panel.setLayout(new BorderLayout());
Panel.add(Panel_up, BorderLayout.NORTH);
Panel.add(ScrollPane,BorderLayout.CENTER);
Panel.add(Panel_down,BorderLayout.SOUTH); this.setTitle("服务器");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400, 300);
this.setLocation(100, 200);
this.add(Panel);
this.setVisible(true); //设置Start监听器;
Start.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
server=new Server(Server_UI.this);
}
}); //设置Say监听器;
Say.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
server.Send_Message(Say_Msg.getText());
Say_Msg.setText("");
}
});
} public static void main(String args[]){
Server_UI serverUI=new Server_UI();
}
}
服务器线程代码:
package com.Server; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList; public class Server extends Thread{
Server_UI ui;
BufferedReader Read;
PrintStream Write;
ServerSocket server;
public Server(Server_UI UI){
this.ui=UI;
//设置服务器的端口;
int port=Integer.parseInt(ui.Port_Msg.getText().trim());
try {
server=new ServerSocket(port);
Println("端口设置成功!");
} catch (IOException e) {
Println("端口设置失败!");
e.printStackTrace();
}
this.ui.clients=new ArrayList<Socket>(); //创建一个线程,用来等待客户端的连接;
new Thread(new Runnable(){
@Override
public void run() {
while(true){
Println("等待客户端接入...");
Socket Client = null;
try {
Client = server.accept();
ui.clients.add(Client);
Println("成功连接到客户端"+Client.toString());
new ListenClient(ui,Client);
} catch (IOException e) {
Println("连接客户端失败!");
Println(Client.toString());
e.printStackTrace();
}
} }
}).start();
} public synchronized void Send_Message(String s){
for(int i=0;i<this.ui.clients.size();i++){
Socket client=ui.clients.get(i);
try {
Write=new PrintStream(client.getOutputStream());
Write.println(s);
} catch (IOException e) {
Println(e.toString());
e.printStackTrace();
}
}
} public void Println(String s){
if(s!=null){
this.ui.Text_show.setText(this.ui.Text_show.getText()+s+"\n");
System.out.println(s + "\n");
}
}
} class ListenClient extends Thread{
public Server_UI ui;
public Socket client;
BufferedReader Read;
PrintStream Write;
public ListenClient(Server_UI UI,Socket Client){
this.ui=UI;
this.client=Client;
//创建一个接受数据的线程;
new Thread(new Runnable(){
@Override
public void run() {
String message="";
while(true){
try {
Read=new BufferedReader(new InputStreamReader(client.getInputStream()));
message=Read.readLine();
Println(message);
} catch (IOException e) {
e.printStackTrace();
}
} } }).start();
}
public void Println(String s){
if(s!=null){
this.ui.Text_show.setText(this.ui.Text_show.getText()+s+"\n");
System.out.println(s + "\n");
}
}
}
[Java小程序]聊天室——Socket和ServerSocket的使用的更多相关文章
- 微信小程序--聊天室小程序(云开发)
微信小程序 -- 聊天室小程序(云开发) 从微信小程序开发社区更新watch接口之后,一直在构思这个项目.项目已经完成很久,但是一直都没有空写一篇博客记录展示一下. 开源地址 wx-cloud-im: ...
- Java实现简易聊天室
Java实现简易聊天室 在学习<Java从入门到精通>这本书,网络通信,基于TCP实现的简易聊天室,我这里对书中的代码略做了修改,做个记录. 这里先放一下运行效果图,代码放在最后. 运行效 ...
- 输出多行字符的一个简单JAVA小程序
public class JAVA { public static void main(String[] args) { System.out.println("-------------- ...
- 浏览器兼容java小程序配置说明
最近在使用的一个web应用系统是内嵌了java小程序,遇到了各种浏览器兼容性问题,现梳理如下: 1.通过以下链接检测当前电脑是否已经安装有java https://java.com/zh_CN/dow ...
- 框架一般用作Java应用程序的窗口,而Applet是Java小程序的窗口
框架一般用作Java应用程序的窗口,而Applet是Java小程序的窗口. 与Frame不同,Applet是在网页中显示的,也可以通过添加Panel进行组件布局. package TomAwt; im ...
- java小程序---简陋版多人聊天室
功能需求: 1 每运行一次主函数,创建一个客户端聊天界面; 2 客户端界面分三块,公屏(显示所有客户端发送的信息),私屏(用于输入个人想要发送的信息),发送按钮(点击一次,将客户端信息发送到服务端) ...
- 用c写一个小的聊天室程序
1.聊天室程序——客户端 客户端我也用了select进行I/O复用,同时监控是否有来自socket的消息和标准输入,近似可以完成对键盘的中断使用. 其中select的监控里,STDOUT和STDIN是 ...
- java多线程控制台聊天室(转)
用java多线程实现一个控制台聊天室,呵呵,好玩! 聊天室服务器端 package tf.thread; import java.io.BufferedReader; import java.io.I ...
- java bio 之聊天室
最近在复习java io相关知识 ,发现很多细节之前没学习到位,原理也没吃透,只能感叹本人愚钝. 复习到bio,顺手写了个简单的聊天室功能,并和大家分享下. 服务端: package io.QQ聊天室 ...
随机推荐
- JavaScript基础 -- js常用内置方法和对象
JS中常用的内置函数如下: 1.eval(str):计算表达式的结果. 2.parseInt(str,n):将符串转换成整数数字形式(可指定几进制). 3.parseFloat(str):将字符串转换 ...
- initial ram disk
1 什么是initial ram disk 它就是一个做好了的文件系统,其存储空间是ram.在kernel启动的第一个阶段,会被mount成根文件系统. 2 为什么需要initial ram disk ...
- jvm实例的个数
Generally speaking, each application will get its own JVM instance and its own OS-level process and ...
- Apache Ignite——集合分布式缓存、计算、存储的分布式框架
Apache Ignite内存数据组织平台是一个高性能.集成化.混合式的企业级分布式架构解决方案,核心价值在于可以帮助我们实现分布式架构透明化,开发人员根本不知道分布式技术的存在,可以使分布式缓存.计 ...
- SPOJ BEADS 最小字符串表示
SPOJ BEADS 给一个字符串(环) 问从哪个字符开始,字典序最小. 可以脑补到很多线性的解法,不过以下这个是最简单的,代码非常简单,就不解释了. #include<iostream> ...
- python实现对excel数据进行修改/添加
import osimport xlrdfrom xlutils.copy import copydef base_dir(filename=None): return os.path.join(os ...
- java 线程开元篇
学习java的读者都知道,Java的每个对象都会有默认的12个方法,这12个方法分别是 object() finalize() hashCode() equals() wait() wait(long ...
- [ZJOI2005]沼泽鳄鱼
题目描述 潘塔纳尔沼泽地号称世界上最大的一块湿地,它地位于巴西中部马托格罗索州的南部地区.每当雨季来临,这里碧波荡漾.生机盎然,引来不少游客. 为了让游玩更有情趣,人们在池塘的中央建设了几座石墩和石桥 ...
- lua调用java java调用lua[转载]
转载:http://dualface.github.io/blog/2013/01/01/call-java-from-lua/LuaJavaBridge - Lua 与 Java 互操作的简单解决方 ...
- C#基础 进制转换6/17
二进制→十进制: 计算公式:a*20+b*21+c*22+…+m*2(n-1) 公式中a为二进制数右边第一位数,b为第二位数,以此类推 例:二进制1011010转换为十进制数为 0*20+1*21+0 ...