先起服务
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();
}
}
分享到:
相关推荐
【标题】:“新手学习简易聊天室” 这是一份专为初学者设计的简易聊天室项目,旨在帮助他们理解和掌握聊天室的基本构建与运作原理。在IT行业中,聊天室是一种常见的实时通讯应用,它允许用户之间进行实时的文字、...
Java课程设计——简易聊天室 在Java编程领域,课程设计是学习过程中不可或缺的一部分,它旨在让学生将所学理论知识应用于实际项目中。本项目“Java课程设计(简易聊天室)”就是一个很好的实践案例,它涵盖了网络...
本项目"基于nio的简易聊天室"旨在通过NIO技术实现一个简单的聊天室服务端和客户端,其特点是有图形用户界面(GUI)供用户交互。 NIO的核心组件包括通道(Channels)、缓冲区(Buffers)和选择器(Selectors)。在这...
【简易聊天室_聊天室_】是一个实现两台主机间通信的应用程序,它允许用户通过互联网进行实时对话。这个项目的核心在于构建一个简单的聊天环境,让用户能够交换各种类型的数据,包括数字、字符、汉字和英文字母。在IT...
【标题】:“简单聊天室简单聊天室简单聊天室C#” 【描述】:“一个简单的聊天室,基于webservice,采用C#编程语言实现。” 【标签】:“简单聊天室”、“简单”、“聊天室”、“聊天”、“C#” 在这个项目中,...
【标题】:“超简易聊天室.(内置对象小实例)”揭示了这是一个关于构建简单聊天室的编程示例,其中可能使用了特定的内置对象,如`APPLICATION`和`SESSION`,来实现用户间的实时交流功能。这两个对象在Web开发中扮演...
(1)制作简易聊天室,能够实现简单的页面聊天功能。 (2)制作网页计数器,要求相同的窗口内刷新页面访问次数并不增加,并且用图片来显数字。1、 熟悉request、response、session、application、out等内置对象; 2、 ...
【基于AJAX的简易聊天室】是一个利用现代Web技术实现的实时交互平台,它整合了AJAX、JSP、Servlet和MySQL数据库等关键技术,旨在提供一个简洁高效的在线沟通环境。AJAX(Asynchronous JavaScript and XML)是核心,...
总结起来,"Java写的简易聊天室"项目涵盖了以下关键知识点: 1. Java的Socket网络编程,包括 `ServerSocket` 和 `Socket` 类。 2. 客户端与服务器之间的连接建立和断开过程。 3. 使用线程处理客户端的并发连接。 4....
本文将深入探讨如何基于C语言构建一个简易聊天室,这是一个非常实用的基础项目,可以帮助初学者更好地理解和掌握网络编程的基本概念。 首先,我们要了解的是TCP/IP协议族,它是互联网通信的基础。在C语言中,我们...
《.NET简易聊天室系统详解》 在编程领域,C#是一种广泛使用的语言,尤其在.NET框架下,它为开发高效、稳定的应用程序提供了强大的支持。本篇文章将深入探讨一个基于C#实现的.NET简易聊天室系统,旨在帮助学习者理解...
【Java简单聊天室源代码】是一个基于Java技术实现的简易聊天室项目,主要涉及的知识点包括Java编程语言、网络通信、多线程以及Web开发中的JSP(Java Server Pages)技术。下面将对这些关键知识点进行详细介绍。 1. ...
【简易聊天室 C语言源程序】是一个针对初学者设计的简单聊天室程序,它通过C语言实现,专注于群聊功能,适用于对聊天室编程感兴趣但经验不足的学生。在这个项目中,我们将探讨聊天室的基本原理、C语言编程技巧以及...
【简易聊天室(PHP+MySQL】是一个基于Web的实时交流平台,主要利用PHP作为服务器端脚本语言,配合MySQL数据库来存储用户信息和聊天记录。这个项目实现了几个关键功能,包括用户注册、发言、查看聊天记录、用户注销...
Java 实现简易聊天室 本文将对 Java 实现简易聊天室的设计和实现进行详细的分析和讲解。该聊天室程序主要由五个 Java 源文件组成,即 Server.java、Objecting.java、LogIn.java、ClientUser.java 和 Client.java。...
【简单聊天室】是一个基础的网络通信应用,它实现了客户端与服务端的实时通信功能,让用户可以进行多人在线聊天。这个项目主要运用了TCP/IP协议,确保数据在互联网中的可靠传输。下面将详细阐述该聊天室的核心知识点...
在本文中,我们将深入探讨如何构建一个简单的Android聊天室应用,以及它与PC服务器端和客户端的交互。这个"Android简易版聊天室"项目旨在提供一个基础架构,用于理解多平台间实时通信的工作原理。 首先,我们要理解...
在Linux环境下创建一个简易聊天室是一项综合性的编程挑战,它涵盖了多个关键的技术领域。这个项目主要涉及以下几个核心知识点: 1. **Linux基本知识**:在Linux操作系统中开发应用程序,需要了解其文件系统、进程...
在本篇《ActiveMQ实战——实现一个简易版的聊天室》中,我们将深入探讨如何利用Apache ActiveMQ构建一个简单的在线聊天应用。ActiveMQ是Apache软件基金会的一个开源项目,它是一款功能强大的消息中间件,用于在...
### C#简易聊天室开发详解 #### 一、项目背景与目标 本项目旨在通过创建一个基于C#和ASP.NET的简易聊天室,帮助学生掌握Web应用开发的基础知识和技术要点。该聊天室具备基本的聊天功能,并且能够利用数据库来管理...