⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 talkapplet.java

📁 java网络高级编程的配套源码,java网络高级编程为清华出版社出版.
💻 JAVA
字号:
/*源程序清单5-22*/import java.net.*;import java.awt.*;import java.awt.event.*;import java.applet.*;import javax.swing.*;import com.borland.jbcl.layout.*;import java.io.*;import java.util.*;public class TalkApplet extends JApplet implements Runnable{  boolean isStandalone = false;  Label userInfo = new Label();  TextField userText = new TextField();  Label label1 = new Label();  TextArea messageText = new TextArea();  Button sendButton = new Button();  java.awt.List userList = new java.awt.List();  URL chatURL;  URLConnection connect;  //用于标识用户是否登录  boolean loggedin=false;  String username;  Thread pollThread=null;  PaneLayout paneLayout1 = new PaneLayout();  /**Get a parameter value*/  public String getParameter(String key, String def)  {    return isStandalone ? System.getProperty(key, def) :      (getParameter(key) != null ? getParameter(key) : def);  }  /**Construct the applet*/  public TalkApplet()  {  }  /**Initialize the applet*/  public void init()  {    try    {      jbInit();    }    catch(Exception e)    {      e.printStackTrace();    }  }  /**Component initialization*/  private void jbInit() throws Exception {    if(pollThread!=null)      return;    userInfo.setText("请输入用户名(请不要超过10个字符):");    this.setSize(new Dimension(400,300));    this.getContentPane().setLayout(paneLayout1);    label1.setText("聊天内容:");    messageText.setEditable(false);    sendButton.setLabel("发送");    sendButton.addActionListener(new java.awt.event.ActionListener() {      public void actionPerformed(ActionEvent e) {        sendButton_actionPerformed(e);      }    });    userText.addActionListener(new java.awt.event.ActionListener() {      public void actionPerformed(ActionEvent e) {        userText_actionPerformed(e);      }    });    this.getContentPane().add(userInfo, new PaneConstraints("userInfo", "userInfo", PaneConstraints.ROOT, 1.0f));    this.getContentPane().add(userText, new PaneConstraints("userText", "userInfo", PaneConstraints.BOTTOM, 0.9166667f));    this.getContentPane().add(messageText, new PaneConstraints("messageText", "userText", PaneConstraints.BOTTOM, 0.90181816f));    this.getContentPane().add(userList, new PaneConstraints("userList", "messageText", PaneConstraints.TOP, 0.24193548f));    this.getContentPane().add(sendButton, new PaneConstraints("sendButton", "userList", PaneConstraints.LEFT, 0.6125f));    this.getContentPane().add(label1, new PaneConstraints("label1", "sendButton", PaneConstraints.BOTTOM, 0.6f));    chatURL=getCodeBase();    int currPriority=Thread.currentThread().getPriority();    int newPriority=currPriority==Thread.MIN_PRIORITY?Thread.MIN_PRIORITY:currPriority-1;    pollThread=new Thread(this,"talkPoll");    pollThread.setDaemon(true);    pollThread.setPriority(newPriority);    pollThread.start();  }  /**Get Applet information*/  public String getAppletInfo()  {    return "Applet Information";  }  /**Get parameter info*/  public String[][] getParameterInfo()  {    return null;  }  public synchronized void start()  {    if(!isLoggedin()&&username!=null)      login();    if(pollThread!=null&&pollThread.isAlive())    {      pollThread.resume();    }    else    {      pollThread=new Thread(this,"talkPoll");      pollThread.setDaemon(true);      pollThread.start();    }  }  //当Applet在浏览器中不可见时,就挂起线程pollthread,并退出"聊天室"  public synchronized void stop()  {    if (pollThread.isAlive())    {      pollThread.suspend();    }    logout();  }  public synchronized void destroy()  {    if (pollThread != null && pollThread.isAlive())    {       pollThread.stop();       pollThread = null;     }     logout();  }  //每隔3秒从服务器中取别的用户输入的信息和加入聊天室的用户  public void run()  {    while (!Thread.interrupted())    {	//若用户已经登陆,则不时的取回别的用户输入的信息	//和机如的的用户名	if (isLoggedin())	{	  pollList();	  poll();	}	//若没有用户登陆,则取回正在聊天室中的用户	else	{	  pollList();	}	try	{	  //睡眠3秒钟	  Thread.sleep(1000*3);	}	catch (InterruptedException e)	{	}      }    }  //登陆到服务器  private void login()  {     if (username ==null) return;     String queryString = "chatservlet?mode=login&user="+URLEncoder.encode(username);     //与服务器通信     try     {	connect = (new URL(chatURL,queryString)).openConnection();	connect.setDefaultUseCaches(false);	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(true);	  showStatus("登录用户名:" + username);	  //提示用户输入信息	  userInfo.setText("请输入你需要发送的信息:");	  repaint();	}	else	{	  showStatus("Error logging in " + response);	  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(username + "离开聊天室!");	}	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("发送信息!");    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("信息发送出去了");       }      else      {	showStatus("发送信息错误 " + 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);    }  }  //返回正在聊天室中的用户  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!");	    return;	  }	  nextLine = in.readLine();	  while (nextLine != null && !nextLine.equals("."))	  {	    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;  }  void sendButton_actionPerformed(ActionEvent e)  {    sendText();  }  void sendText()  {    if (isLoggedin())    {   	send();    }    else    {	username = userText.getText();	if (username.length()>10)	{  	  showStatus("请不要超过10个字符!");	}	else	{	  userText.setText("");	  login();	}      }  }  void userText_actionPerformed(ActionEvent e)  {    sendText();  }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -