与现在所使用的的qq微信群聊发送消息类似
/**
* 一对多聊天服务应用,与群聊相同
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
/**
* 接受客户端发来消息的线程类
*/
class ChatRec extends Thread{
private Socket socket;
public ChatRec(Socket socket){
this.socket=socket;
}
@Override
public void run() {
this.receiveMsg();
}
/**
*实现接受客户端发的消息
*/
private void receiveMsg(){
BufferedReader br =null;
try{
br =new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
while(true){
String msg = br.readLine();
synchronized ("abc"){
//读取到数据写入公共数据区
CharRoomServer.buf="["+this.socket.getInetAddress()+"]"+msg;
//唤醒发送消息的线程对象
"abc".notifyAll();
}
}
}catch (Exception e){
e.printStackTrace();
}finally {
if (br!=null){
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (this.socket!=null){
try {
this.socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
/**
* 向客户端发送消息的线程类
*/
class ChatSend extends Thread{
private Socket socket;
public ChatSend(Socket socket){
this.socket =socket;
}
@Override
public void run() {
this.sengMsg();
}
/**
* 将公共数据区的消息发送给客户端
*/
private void sengMsg(){
PrintWriter pw =null;
try{
pw =new PrintWriter(this.socket.getOutputStream());
while(true){
synchronized ("abc"){
//发送消息线程处于等待
"abc".wait();
//将公共数据区发送
pw.println(CharRoomServer.buf);
pw.flush();
}
}
}catch (Exception e){
e.printStackTrace();
}finally {
if (pw!=null){
pw.close();
}
if(this.socket!=null){
try {
this.socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public class CharRoomServer {
//定义公共数据区
public static String buf;
public static void main(String[] args) {
System.out.println("聊天室版本1.0");
System.out.println("服务区监听端口8888");
ServerSocket serverSocket =null;
try{
serverSocket =new ServerSocket(8888);
while(true){
Socket socket= serverSocket.accept();
System.out.println("连接到"+socket.getInetAddress());
new ChatRec(socket).start();
new ChatSend(socket).start();
}
}catch (Exception e){
e.printStackTrace();
}finally {
if (serverSocket!=null){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}