简单聊天室


先起服务
import java.io.*;
import java.net.*;
import java.util.*;
import java.applet.*;
public class ChatServer implements Runnable {
public final static int DEFAULT_PORT = 2000;
public final static int DEFAULT_MAX_BACKLOG = 5;
public final static int DEFAULT_MAX_CONNECTIONS = 20;
public final static String DEFAULT_HOST_FILE = "hosts.txt";
public final static String DEFAULT_SOUND_FILE = "file:gong.au";
public final static String MAGIC = "Yippy Skippy";
private String magic = MAGIC;
private int port = DEFAULT_PORT;
private int backlog = DEFAULT_MAX_BACKLOG;
private int numConnections = 0;
private int maxConnections = DEFAULT_MAX_CONNECTIONS;
private String hostfile = DEFAULT_HOST_FILE;
private String soundfile = DEFAULT_SOUND_FILE;
private Vector connections = null;
private AudioClip connectSound = null;
private Hashtable hostInfo = new Hashtable(15);
public static void main(String[] args) {
ChatServer cs = new ChatServer();
cs.go();
}
public void go() {
String portString = System.getProperty("port");
if (portString != null)
port = Integer.parseInt(portString);
String backlogString = System.getProperty("backlog");
if (backlogString != null)
backlog = Integer.parseInt(backlogString);
String hostFileString = System.getProperty("hostfile");
if (hostFileString != null)
hostfile = hostFileString;
String soundFileString = System.getProperty("soundfile");
if (soundFileString != null)
soundfile = soundFileString;
String magicString = System.getProperty("magic");
if (magicString != null)
magic = magicString;
String connections = System.getProperty("connections");
if (connections != null)
maxConnections = Integer.parseInt(connections);
this.connections = new Vector(maxConnections);
System.out.println("Server settings:\n\tPort=" + port
+ "\n\tMax Backlog=" + backlog + "\n\tMax Connections="
+ maxConnections + "\n\tHost File=" + hostfile
+ "\n\tSound File=" + soundfile);
createHostList();
try {
URL sound = new URL(soundfile);
connectSound = Applet.newAudioClip(sound);
} catch (Exception e) {
e.printStackTrace();
}
this.port = port;
Thread t = new Thread(this);
t.start();
}
private void createHostList() {
File hostFile = new File(hostfile);
try {
System.out.println("Attempting to read hostfile hosts.txt: ");
FileInputStream fis = new FileInputStream(hostFile);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String aLine = null;
while ((aLine = br.readLine()) != null) {
int spaceIndex = aLine.indexOf(' ');
if (spaceIndex == -1) {
System.out.println("Invalid line in host file: " + aLine);
continue;
}
String host = aLine.substring(0, spaceIndex);
String student = aLine.substring(spaceIndex + 1);
System.out.println("Read: " + student + "@" + host);
hostInfo.put(host, student);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void run() {
ServerSocket serverSocket = null;
Socket communicationSocket;
try {
System.out.println("Attempting to start server...");
serverSocket = new ServerSocket(port, backlog);
} catch (IOException e) {
System.out.println("Error starting server: Could not open port "
+ port);
e.printStackTrace();
System.exit(-1);
}
System.out.println("Started server on port " + port);
// Run the listen/accept loop forever
while (true) {
try {
// Wait here and listen for a connection
communicationSocket = serverSocket.accept();
HandleConnection(communicationSocket);
} catch (Exception e) {
System.out.println("Unable to spawn child socket.");
e.printStackTrace();
}
}
}

public void HandleConnection(Socket connection) {
synchronized (this) {
while (numConnections == maxConnections) {
try {
wait();
} catch (Exception e) {
e.printStackTrace();
}
}
}
numConnections++;
Connection con = new Connection(connection);
Thread t = new Thread(con);
t.start();
connections.addElement(con);
}

public synchronized void connectionClosed(Connection connection) {
connections.removeElement(connection);
numConnections--;
notify();
}

public void sendToAllClients(String message) {
Enumeration cons = connections.elements();
while (cons.hasMoreElements()) {
Connection c = (Connection) cons.nextElement();
c.sendMessage(message);
}
}
class Connection implements Runnable {
private Socket communicationSocket = null;
private OutputStreamWriter out = null;
private BufferedReader in = null;
public void run() {
OutputStream socketOutput = null;
InputStream socketInput = null;
try {
socketOutput = communicationSocket.getOutputStream();
out = new OutputStreamWriter(socketOutput);
socketInput = communicationSocket.getInputStream();
in = new BufferedReader(new InputStreamReader(socketInput));
InetAddress address = communicationSocket.getInetAddress();
String hostname = address.getHostName();
String welcome = "Connection made from host: " + hostname
+ "\nEverybody say hello";
String student = (String) (hostInfo.get(hostname));
if (student != null)
welcome += " to " + student;
welcome += "!\n";
ChatServer.this.sendToAllClients(welcome);
System.out.println("Connection made " + student + "@"
+ hostname);
sendMessage("Welcome " + student + " the passphrase is "
+ magic + "\n");
String input = null;

while ((input = in.readLine()) != null) {
if (input.indexOf(magic) != -1 && connectSound != null) {
connectSound.play();
sendMessage("Congratulations " + student
+ " you sent the passphrase!\n");
System.out.println(student + " sent the passphrase!");
} else
ChatServer.this.sendToAllClients(input + "\n");
}
} catch (Exception e) {
} finally {
try {
if (in != null)
in.close();
if (out != null)
out.close();
communicationSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
ChatServer.this.connectionClosed(this);
}
}
public Connection(Socket s) {
communicationSocket = s;
}
public void sendMessage(String message) {
try {
out.write(message);
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}

}
客户端

import java.awt.*;
import java.io.*;
import java.net.*;
import java.awt.event.*;
public class ChatRoom {
private TextArea outPut;
private TextField inPut;
private Button sendButton;
private Button quitButton;
private Choice namesList;
private MenuItem quit;
private MenuItem about;
private Dialog aboutDialog;
private Socket clientSocket = null;
private BufferedReader in;
private PrintStream out;
public ChatRoom() {
outPut = new TextArea(10, 50);
inPut = new TextField(50);
namesList = new Choice();
sendButton = new Button("SEND");
quitButton = new Button("QUIT");
quit = new MenuItem("Quit");
about = new MenuItem("About");
}

public void display() {
Frame frame = new Frame();
Panel p = new Panel();
namesList.add("Grand Poobah");
namesList.add("The Man");
namesList.add("Java Geek");
p.add(sendButton);
p.add(quitButton);
p.add(namesList);
frame.add(outPut, BorderLayout.WEST);
frame.add(p, BorderLayout.CENTER);
frame.add(inPut, BorderLayout.SOUTH);
MenuBar menuBar = new MenuBar();
Menu file = new Menu("File");
Menu help = new Menu("Help");

file.add(quit);
help.add(about);
menuBar.add(file);
menuBar.setHelpMenu(help);
frame.setMenuBar(menuBar);
frame.setVisible(true);
frame.setSize(512, 241);

aboutDialog = new AboutDialog(frame, "About", true);
quit.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e) {
out.println("User wang has been exit \n");
System.exit(0);
}

}
);
quitButton.addActionListener(new ActionListener(){

public void actionPerformed(ActionEvent e) {
out.println("User wang has been exit \n");
System.exit(0);
}
});
frame.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent e){
out.println("User wang has been exit \n");
System.exit(0);

}
});
inPut.addActionListener(new InputListener());
sendButton.addActionListener(new SendListener());
about.addActionListener(new AboutListener());
docennect();

}
class AboutDialog extends Dialog implements ActionListener{
public AboutDialog(Frame fr,String name,boolean statement){
super(fr,name,statement);
add(new Label("The ChatClient is a neat tool that allows you to talk " +
"to other ChatClients via a ChatServer"),BorderLayout.NORTH);
Button b = new Button("OK");
add(b,BorderLayout.SOUTH);
pack();
b.addActionListener(this);
}

public void actionPerformed(ActionEvent e) {
aboutDialog.setVisible(false);
}

}

class AboutListener implements ActionListener{
public void actionPerformed(ActionEvent e){
aboutDialog.setVisible(true);
}
}
class InputListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
copyText();
}
}
class SendListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
copyText();
}
}
public void copyText(){
String text=inPut.getText();
out.println(namesList.getSelectedItem()+":"+text);
inPut.setText("");
}
public void docennect(){
try{ clientSocket=new Socket("127.0.0.1",2000);
in=new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out=new PrintStream(clientSocket.getOutputStream());
out.println("User wang has been Login\n");
Thread t=new Thread(new DisplayReader());
t.start();
}
catch(Exception e1){

}


}
class DisplayReader implements Runnable{
private boolean keepListener=true;
public void run() {
while(keepListener){
try{String nextLine=in.readLine();
outPut.append(nextLine+"\n");
}
catch(Exception e){
keepListener=false;
e.printStackTrace();

}

}

}


}


public static void main(String[] args) {
ChatRoom chatRoom=new ChatRoom();
chatRoom.display();
}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值