java 用socket制作一个简易多人聊天室
代码:
服务器端Server
import java.io.*;
import java.net.*;
import java.util.ArrayList;
public class Server{
public static ServerSocket server_socket;
public static ArrayList<Socket> socketList=new ArrayList<Socket>();
public static void main(String []args){
try{
server_socket = new ServerSocket(5000);
while(true){
Socket socket = server_socket.accept();
socketList.add(socket); //把sock对象加入sock集合
ServerBO_Thread st=new ServerBO_Thread(socket,socketList); //初始化多线程
st.start();//启动多线程
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
try{
if(server_socket!=null){
server_socket.close();
}
}catch(Exception ex){
ex.printStackTrace();
}
}
}
public void encryptWrite(String src,DataOutputStream output)throws IOException{
//将一个字符串转化为字符数组
//System.out.println(src);
char[] char_arr = src.toCharArray();
//加密操作
for(int i = 0;i<char_arr.length;i++){
output.writeChar(char_arr[i]+13);
}
//用作结束标志符
output.writeChar(2333);
output.flush();
}
//读取并解密
public String readDecrypt(DataInputStream input)throws IOException{
String rtn="";
while(true){
int char_src =input.readChar();
if(char_src!=2333){
rtn=rtn+(char)(char_src-13);
}else{
break;
}
}
return rtn;
}
}
class ServerBO_Thread extends Thread{
Socket client = null;
ArrayList<Socket> clients;
ServerBO_Thread(Socket s,ArrayList<Socket> ss){//初始化
client=s;
clients=ss;
}
public void run(){
DataInputStream input = null;
DataOutputStream output =null;
try{
input = new DataInputStream(client.getInputStream());
Server bo = new Server();
String receive=null;
String send=null;
while(true){//监视当前客户端有没有发来消息
if(!client.isClosed()){
receive=bo.readDecrypt(input);
clients.trimToSize();
String[] param = receive.split("&");
if(")start".equals(param[1])){ //分析客户端发来的内容
send = param[0]+"进入聊天室";
}else{
send = param[0]+"说: "+param[1];
}
if(!("3333".equals(param[1]))){//3333为退出聊天室信号
for(Socket socket:clients){ //遍历socke集合
//把读取到的消息发送给各个客户端
if(!socket.isClosed()){
output = new DataOutputStream(socket.getOutputStream());
bo.encryptWrite(send,output);
}
}
}else{//如果有客户端退出
for(Socket socket:clients){ //遍历socke集合
if(socket!=client){//告诉其他人此人退出聊天室
if(!(socket.isClosed())){
output = new DataOutputStream(socket.getOutputStream());
bo.encryptWrite(param[0]+"已退出聊天室",output);
}
}
}
output = new DataOutputStream(client.getOutputStream());
bo.encryptWrite("3333",output);//返回信号给要退出的客户端,然后关闭线程
client.close();
input.close();
output.close();
}
}else{
break;
}
}
}catch(Exception ex){
ex.printStackTrace();
}
}
}
客户端:
import java.io.IOException;
import java.util.Scanner;
import java.net.*;
import java.io.*;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.DataOutputStream; public class People{
//服务端ip
public String ip = "127.0.0.1";
//服务端端口
public int port = 5000;
public DataOutputStream output = null;
public Socket socket = null;
public DataInputStream input = null;
public Scanner sc =new Scanner (System.in);
public String send ;
public String receive;
public String name;
public String sd = null;
public static void main(String[]aa){
People po = new People();
po.start();
}
public void start(){
try{
System.out.println("*******欢迎使用匿名聊天室!**********");
System.out.println("请输入你将要使用的昵称:");
name=sc.nextLine();//获取昵称
socket = new Socket(ip,port);
output=new DataOutputStream(socket.getOutputStream());
input = new DataInputStream(socket.getInputStream());
send = name+"&)start";//把昵称发送到server 告诉所有人有新成员加入聊天室
System.out.println("(如果要退出聊天室请输入“3333”!)");
System.out.println("*******成功进入匿名聊天室!**********");
System.out.println("");
encryptWrite(send,output);
Out out=new Out(output,name,input,socket);
out.start();//启动发送聊天内容的多线程
while(true){
String receive = readDecrypt(input);
if("3333".equals(receive)){//如果收到“3333”则退出聊天室
System.out.println("*******成功退出匿名聊天室!**********");
input.close();
output.close();
socket.close();
System.exit(0);
}
System.out.println(receive);
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
try{
if(socket!=null) socket.close();
input.close();
output.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
public void encryptWrite(String src,DataOutputStream output)throws IOException{
//将一个字符串转化为字符数组
char[] char_arr = src.toCharArray();
//加密操作
for(int i = 0;i<char_arr.length;i++){
output.writeChar(char_arr[i]+13);
}
//用作结束标志符
output.writeChar(2333);
output.flush();
}
//读取并解密
public String readDecrypt(DataInputStream input)throws IOException{
String rtn="";
while(true){
int char_src =input.readChar();
if(char_src!=2333){
rtn=rtn+(char)(char_src-13);
}else{
break;
}
}
return rtn;
}
}
class Out extends Thread {
public DataOutputStream output;
public DataInputStream input;
public static String name;
public Socket socket;
public Scanner sc =new Scanner (System.in);
Out(DataOutputStream ot,String n,DataInputStream it,Socket socket){
output=ot;
input=it;
name=n;
}
public void run(){
People po = new People();
try{
while(true){
String send=sc.nextLine();//获取用户输入
String send2=name+"&"+send;//把聊天内容打包成约定形式
po.encryptWrite(send2,output);
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
System.out.println("sfef");
}
}
}
实现效果:

实验心得:
1、用于接收信息的字符串每次都要重新定义一个,不能在开头只定义一次,这样会导致数组角标异常的错误,因为每次接收到的信息的长度都不一样的,所以每次用都要重新new一个字符串。
2、调用多线程的时候一定要把socket或者input output参数传递给构造函数初始化,不能用类.output的形式调用,不然会有空指针的错误(原因大概是直接调用的可能是还没初始化的)。
3、为了程序的健壮性,我们需要对当有客户端退出聊天室的情况进行处理,如果不处理,当有人强制退出聊天室时会导致服务端崩溃发生空指针异常。在这个程序主中我约定用“3333”为退出信息,当客户端发出3333时即退出聊天室,关闭对应socket,此处关键点是要理清谁先关闭谁后关闭,不然也会导致socket崩溃,流程应该是发送3333告知服务器端我要退出了,然后服务器返回信号给客户端我已知晓,你可以退出了,然后客户端服务器端才可以关闭socket
java 用socket制作一个简易多人聊天室的更多相关文章
- Python基于Socket实现简易多人聊天室
前言 套接字(Sockets)是双向通信信道的端点. 套接字可以在一个进程内,在同一机器上的进程之间,或者在不同主机的进程之间进行通信,主机可以是任何一台有连接互联网的机器. 套接字可以通过多种不同的 ...
- Python编写基于socket的非阻塞多人聊天室程序(单线程&多线程)
前置知识:socket非阻塞函数(socket.setblocking(False)),简单多线程编程 代码示例: 1. 单线程非阻塞版本: 服务端: #!/usr/bin/env python # ...
- Python实现网络多人聊天室
网络多人聊天室 文件结构: chatroom ├── client.py # 客户端代码 ├── language.py # 语言文件 ├── server.py # 服务端代码 └── set ...
- java socket之多人聊天室Demo
一.功能介绍 该功能实现了一个类似QQ的最简单多人聊天室,如下图所示. 二.目录结构 三.服务端 1)SocketServer类,该类是服务端的主类,主要负责创建聊天窗口,创建监听客户端的线程: pa ...
- 与众不同 windows phone (31) - Communication(通信)之基于 Socket UDP 开发一个多人聊天室
原文:与众不同 windows phone (31) - Communication(通信)之基于 Socket UDP 开发一个多人聊天室 [索引页][源码下载] 与众不同 windows phon ...
- 与众不同 windows phone (30) - Communication(通信)之基于 Socket TCP 开发一个多人聊天室
原文:与众不同 windows phone (30) - Communication(通信)之基于 Socket TCP 开发一个多人聊天室 [索引页][源码下载] 与众不同 windows phon ...
- 用XMLHttpRequest制作一个简易ajax
概述 jquery退出历史舞台之后,我们怎么来发送ajax请求呢?可以用相关的库,也可以自己制作一个简易的ajax. 需要说明的是,我们使用的是XMLHttpRequest 2,它几乎兼容所有主流浏览 ...
- 使用 history 对象和 location 对象中的属性和方法制作一个简易的网页浏览工具
查看本章节 查看作业目录 需求说明: 使用 history 对象和 location 对象中的属性和方法制作一个简易的网页浏览工具 实现思路: 使用history对象中的 forward() 方法和 ...
- java 通过TCP\UDP 协议实现多人聊天,点对点,文件传送-----分服务器端和客户端
java 通过TCP\UDP 协议实现多人聊天,点对点,文件传送-----分服务器端和客户端 启动界面如下图: 首先启动服务器: 客户端登陆,登陆成功后为: 默认发送是全部用户,是多人发送. 当在边列 ...
随机推荐
- mysql-proxy之奇虎360 Atlas 安装实现mysql读写分离
官方git https://github.com/Qihoo360/Atlas 参照:http://blog.qixingzhong.com/2013/09/centos-install-atlas. ...
- linux gitlab nginx 安装 配置
更新:bitnami-gitlab 7.8版本后界面发生变化 邮件问题: cd /data/server/gitlab/apps/gitlab/htdocs/config vim environmen ...
- MVC 上传文件并展示
最近悟出来一个道理,在这儿分享给大家:学历代表你的过去,能力代表你的现在,学习代表你的将来. 十年河东十年河西,莫欺少年穷 学无止境,精益求精 最近在做自学MVC,遇到的问题很多,索性一点点总结 ...
- 从零开始攻略PHP(8)——面向对象(下)
8.编写代码类 每个分离的函数可以执行一个明确的任务.任务越简单,编写与测试这个函数就越简单,当然也不要将这个函数分得太小——若将程序分成太多的小个体,读起来就会很困难. 使用继承可以重载操作.我们可 ...
- Java基础(35):装箱与拆箱---Java 中基本类型和包装类之间的转换(Wrapper类)
基本类型和包装类之间经常需要互相转换,以 Integer 为例(其他几个包装类的操作雷同哦): 在 JDK1.5 引入自动装箱和拆箱的机制后,包装类和基本类型之间的转换就更加轻松便利了. 那什么是装箱 ...
- Android Notification通知栏使用
package com.example.mynotifycation; import android.app.Activity; import android.app.Notification; im ...
- paper 47 :Latex中文显示(转)
中文支持需要cjk-latex,总得来说中文可以使用GB和GBK两种字体,GBK需要从windows下copy *.ttc或*.ttf, GB字体则在linux下就用. 先说支持GB的中文显示,安装以 ...
- Easyui主从表设计
js代码: // 全局变量 var loading; var grid; var mainGrid; var dlg_Edit; var dlg_Edit_form; var virpath = &q ...
- oracle表分区
注:新建分区表前要先准备好要用的表空间 一. oracle分区类型: 范围分区(Range分区) 列表分区(List分区) 散列分区(Hash分区) 组合分区(Composite Partitioni ...
- vim多行缩进的方法
在visual模式下选中要缩进的行,然后按>