📄 chatapplet.java
字号:
/*源程序清单5-22*/
import java.applet.Applet;
import java.awt.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.net.MalformedURLException;
import java.io.*;
import java.util.*;
public class ChatApplet extends Applet implements Runnable
{
//用于提醒客户输入用户名或信息
Label userInfo;
//用于标识显示聊天内容的区域
Label messageInfo;
//用于标识显示正在"聊天室"的用户的区域;
Label listInfo;
//用于发送用户输入的用户名或信息;
Button sendButton;
//用于接收用户输入的信息;
TextField userText;
//用于显示聊天内容;
TextArea messageText;
//用于保存正在"聊天室"的用户
List userList;
//用户建立与服务器的连接
URL chatURL;
URLConnection connect;
//用于标识用户是否登录
volatile private boolean loggedin=false;
String username;
Thread pollThread=null;
//返回描述applet的信息
public String getAppletInfo()
{
return "ChatApplet -applet to communicate with ChatServlet, written by ding song";
}
public synchronized void init()
{
if(pollThread!=null)
return;
super.init();
resize(500,300);
userInfo=new Label("Enter User Name(Max 10 char):");
messageInfo=new Label("Message Text:");
userText=new TextField(40);
sendButton=new Button("Send");
messageText=new TextArea(10,40);
messageText.setEditable(false);
Panel mainPanel=new Panel();
GridBagLayout gbl=new GridBagLayout();
GridBagConstraints gbc=new GridBagConstraints();
gbc.weightx=0;
gbc.weighty=0;
gbc.gridx=0;
gbc.gridy=0;
gbc.gridwidth=10;
gbc.gridheight=1;
gbc.anchor=GridBagConstraints.CENTER;
gbc.fill=GridBagConstraints.NONE;
mainPanel.setLayout(gbl);
gbl.setConstraints(userInfo,gbc);
mainPanel.add(userInfo);
gbc.gridy=1;
gbc.gridwidth=9;
gbc.fill=GridBagConstraints.HORIZONTAL;
gbl.setConstraints(userText,gbc);
mainPanel.add(userText);
gbc.gridx=9;
gbc.gridwidth=1;
gbc.fill=GridBagConstraints.NONE;
gbl.setConstraints(sendButton,gbc);
mainPanel.add(sendButton);
gbc.gridx=0;
gbc.gridy=2;
gbc.gridwidth=10;
gbl.setConstraints(messageInfo,gbc);
mainPanel.add(messageInfo);
gbc.gridy=3;
gbc.weighty=100;
gbc.gridheight=10;
gbc.fill=GridBagConstraints.BOTH;
gbl.setConstraints(messageText,gbc);
mainPanel.add(messageText);
Panel userPanel=new Panel();
userPanel.setLayout(new BorderLayout());
userPanel.add("North",listInfo);
userList=new List(10,false);
userList.addItem("None logged in");
userPanel.add("Center",userList);
setLayout(new BorderLayout());
add("Center",mainPanel);
add("East",userPanel);
chatURL=getCodeBase();
int currPriority=Thread.currentThread().getPriority();
int newPriority=currPriority==Thread.MIN_PRIORITY?Thread.MIN_PRIORITY:currPriority-1;
pollThread=new Thread(this,"ChatPoll");
pollThread.setDaemon(true);
pollThread.setPriority(newPriority);
pollThread.start();
p("Chat:starting polling");
}
public synchronized void start()
{
if(!isLoggedin()&&username!=null)
login();
if(pollThread!=null&&pollThread.isAlive())
{
pollThread.resume();
p("Chat:resuming poll");
}
else
{
p("Chat:No poll thread!");
pollThread=new Thread(this,"ChatPoll");
pollThread.setDaemon(true);
pollThread.start();
p("Chat:starting poll");
}
}
//当Applet在浏览器中不可见时,就挂起线程pollthread,并退出"聊天室"
public synchronized void stop()
{
if (pollThread.isAlive())
{
pollThread.suspend();
p("Chat:suspending poll");
}
else
{
p("Chat:Dead poll thread in stop()!");
}
logout();
}
//当用户退出浏览器时,删除线程pollthread,退出聊天室
public synchronized void destroy()
{
if (pollThread != null && pollThread.isAlive())
{
pollThread.stop();
pollThread = null;
p("Chat:stopping poll!");
}
logout();
}
//每隔3秒从服务器中取别的用户输入的信息和加入聊天室的用户
public void run()
{
p("Chat: starting the poll run");
while (!Thread.interrupted())
{
//若用户已经登陆,则不时的取回别的用户输入的信息
//和机如的的用户名
if (isLoggedin())
{
pollList();
poll();
p("Chat:poll!");
}
//若没有用户登陆,则取回正在聊天室中的用户
else
{
pollList();
p("Chat: not loggeding for poll!");
}
try
{
//睡眠3秒钟
Thread.sleep(1000*3);
}
catch (InterruptedException e)
{
}
}
p("Chat: exiting run()!");
}
//登陆到服务器
private void login()
{
if (username ==null) return;
String queryString = "chatservlet?mode=login&user="
+URLEncoder.encode(username);
p("Attemping login as " + username);
//与服务器通信
try
{
connect = (new URL(chatURL,queryString)).openConnection();
connect.setDefaultUseCaches(false);
connect.setUseCaches(false);
connect.setDoInput(true);
connect.setDoOutput(false);
connect.connect();
p("Mading connection to " + connect);
DataInputStream in = new DataInputStream(connect.getInputStream());
String response = in.readLine();
if (response.startsWith("+"))
{
//标识用户已经登陆
setLoggedin(true);
showStatus("Logged into chat as user " + username);
p("Logged in as " + username);
//提示用户输入信息
userInfo.setText("Type message:");
repaint();
}
else
{
showStatus("Error logging in " + response);
p("Could not log in as " + username);
System.err.println("Error logging in " + response);
}
}
catch (MalformedURLException e2)
{
System.err.println("MalformedURLException logging in!");
e2.printStackTrace(System.err);
showStatus("Error logging in!");
}
catch (IOException e1)
{
System.err.println("IOException logging in!");
e1.printStackTrace(System.err);
showStatus("Error logging in!");
}
}
//退出聊天室
private void logout()
{
if (!isLoggedin() || username ==null)
{
return;
}
String queryString = "chatservlet?mode=logout&username=" +
URLEncoder.encode(username);
//与服务器通信
try
{
connect = (new URL(chatURL,queryString)).openConnection();
connect.setUseCaches(false);
connect.setDoInput(true);
connect.setDoOutput(false);
connect.connect();
DataInputStream in = new DataInputStream(connect.getInputStream());
String response = in.readLine();
if (response.startsWith("+"))
{
//标识用户已经退出聊天室
setLoggedin(false);
showStatus("User " + username + "Logged out of Chat!");
}
else
{
showStatus("Error logging out" + response);
System.err.println("Error logging out" + response);
}
}
catch (MalformedURLException e2)
{
System.err.println("MalformedURLException logging out!");
e2.printStackTrace(System.err);
showStatus("Error logging out!");
}
catch (IOException e1)
{
System.err.println("IOException logging out!");
e1.printStackTrace(System.err);
showStatus("Error logging out!");
}
}
//发送用户输入的信息
private void send()
{
String message = userText.getText();
//用户输入空字符串不发送
if (message.equals(""))
{
return;
}
//清除用户在Applet中输入的内容
userText.setText("");
showStatus("Sending message!");
String queryString = "chatservlet?mode=send&user="+
URLEncoder.encode(username);
queryString = queryString + "&message="+URLEncoder.encode(message);
try
{
connect = (new URL(chatURL,queryString)).openConnection();
connect.setUseCaches(false);
connect.setDoInput(true);
connect.setDoOutput(false);
connect.connect();
DataInputStream in = new DataInputStream(connect.getInputStream());
String response = in.readLine();
if (response.startsWith("+"))
{
showStatus("Message sent!");
}
else
{
showStatus("Error sending message " + response);
System.err.println("Error sending message " + response);
}
}
catch (MalformedURLException e2)
{
System.err.println("MalformedURLException logging in!");
e2.printStackTrace(System.err);
showStatus("Error logging in!");
}
catch (IOException e1)
{
System.err.println("IOException logging in!");
e1.printStackTrace(System.err);
showStatus("Error logging in!");
}
}
//返回所有用户输入的信息
private void poll()
{
String queryString = "chatservlet?mode=poll&user=" +
URLEncoder.encode(username);
try
{
DataInputStream in = new DataInputStream(
new URL(chatURL,queryString).openStream());
String nextLine = in.readLine();
if (!nextLine.startsWith("+"))
{
showStatus("Error getting messages from server!");
System.err.println("Error getting messages from server!");
return;
}
nextLine = in.readLine();
while (nextLine != null && !nextLine.equals("."))
{
System.err.println(nextLine);
messageText.appendText(nextLine + "\r\n");
repaint();
nextLine = in.readLine();
}
}
catch (IOException e)
{
System.err.println("IOException poll!");
e.printStackTrace(System.err);
showStatus("Error Checking Message!");
}
}
//返回正在聊天室中的用户
private void pollList()
{
String queryString = "chatservlet?mode=list";
Vector users = new Vector();
try
{
URL listURL = new URL(chatURL,queryString);
URLConnection listConn = listURL.openConnection();
listConn.setDefaultUseCaches(false);
listConn.setUseCaches(false);
listConn.connect();
DataInputStream in = new DataInputStream(
listConn.getInputStream());
String nextLine = in.readLine();
if (!nextLine.startsWith("+"))
{
showStatus("Error getting userlist from server!");
p("Error getting userlist from server");
return;
}
nextLine = in.readLine();
while (nextLine != null && !nextLine.equals("."))
{
p("Read user: " + nextLine);
users.addElement(nextLine);
nextLine = in.readLine();
}
//清除旧的用户表,加入新的
if (!users.isEmpty())
{
userList.clear();
int size = users.size();
for (int I=0;I<size ;I++ )
{
userList.addItem((String)users.elementAt(I));
}
}
else
{
userList.clear();
userList.addItem("None logged in!");
}
repaint();
}
catch (IOException e)
{
System.err.println("IOException poll!");
e.printStackTrace(System.err);
showStatus("Error Checking Message!");
}
}
//判断用户是否已经登陆到聊天室
public boolean isLoggedin()
{
return loggedin;
}
//设置用户是否登陆的状态
protected void setLoggedin(boolean newval)
{
loggedin = newval;
}
//处理用户的动作
public boolean action(Event evt, Object arg)
{
//用户按下按钮和输入信息后按下回车
if (evt.target == sendButton || evt.target == userText)
{
if (isLoggedin())
{
send();
}
else
{
username = userText.getText();
if (username.length()>10)
{
showStatus("10 or fewer characters,please!");
}
else
{
userText.setText("");
login();
}
}
return true;
}
return super.action(evt,arg);
}
private void p(String debug)
{
System.err.println("Chat: " + debug);
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -