日期:2014-05-20 浏览次数:20841 次
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
public class SocketManager extends ArrayList {
synchronized void add(Socket socket){
super.add(socket);
}
synchronized void delete(Socket socket){
super.remove(socket);
}
synchronized void sendClientCount(){
String info = "当前聊天人数"+size();
System.out.println(info);
writeAll(info);
}
synchronized void writeAll(String str){
PrintWriter writer = null;
Socket socket;
for(int i=0;i<size();i++){
socket = (Socket)get(i);
try {
writer = new PrintWriter(socket.getOutputStream(),true);//创建输出流
if(writer != null){
writer.println(str);//通过输出流写入信息
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerProcess {
private SocketManager socketMan = new SocketManager();
void getServer(){
try{
ServerSocket serverSocket = new ServerSocket(7777);
System.out.println("服务器套接字已创建");
while(true){
Socket socket = serverSocket.accept(); //等待连接
new write_Thread(socket).start(); //启动线程
socketMan.add(socket); //添加套接字
socketMan.sendClientCount(); //将连接数输出
}
}catch(Exception e){
e.printStackTrace();
}
}
class write_Thread extends Thread{
Socket socket = null;
private BufferedReader reader;
public write_Thread(Socket socket){
this.socket = socket;
}
public void run(){
try{
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String msg;
while((msg=reader.readLine())!= null){
//System.out.println(msg);
socketMan.writeAll(msg);
}
}catch(Exception e){
e.printStackTrace();
}
}
}
public static void main(String[] args){
ServerProcess server = new ServerProcess();
server.getServer();
}
}
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
public class Client2 extends JFrame{
private static final long serialVersionUID = 1L;
private JPanel jpanel = new JPanel();
private JLabel nameLabel = new JLabel("姓名:");
private JTextField nameField = new JTextField();
private JTextArea msgArea = new JTextArea();
private JTextField sendField = new JTextField();
private JScrollPane jScrollPanel = new JScrollPane();
private BufferedReader reader;
private PrintWriter writer;
private Socket socket;
public Client2(String title){
super(title);