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

📄 205bf7571dd80019154b87f6f34182dd

📁 使用TCP和UDP协议
💻
📖 第 1 页 / 共 2 页
字号:
/*
 * Created on 2005-5-28
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package client;

/**
 * @author Administrator
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import java.io.*;
import java.net.*;

public class PublicChatGUI extends JFrame
{
    TCPConnection tcpConnection = null;
	private JPanel panel = null;
	private JTextArea messageArea = null;
	private JTextArea inputArea = null;
	private JButton exitButton = null;
	private JButton sendButton = null;
	private JMenuBar menuBar = null;
	private JToolBar toolBar = null;
    DefaultListModel lItems = new DefaultListModel();
	private JList list = null;
	private String userName = null;
	private String privateReceiver = null;
	String messageToBeSent = null;
	byte[] byteArray = new byte[1024];
	
	//修改字体用:
	Font font;
	String fontFamily = null;
	int fontSize = 0;
	int fontStyle = 0;
	
	String host = "localhost";
	int port = 1234;
	int udpPort = 1235;
	
	//用于UDP传输
	ObjectOutputStream objectOutput;
    ByteArrayOutputStream byteArrayStream;
	
	boolean hasLogin = false;
	
	public static final String PROMPT = "[System]       ", ERROR = "[Error]           ", EXCEPTION = "[Exception]  ";
	
	public String getMessageAreaText()
	{
	    return messageArea.getText();
	}
	public void setMessageAreaText(String text)
	{
	    messageArea.setText(text);
	}
	public void appendMessageAreaText(String text)
	{
	    messageArea.append(text + "\n");
	}
	
	public String getinputAreaText()
	{
	    return inputArea.getText();
	}
	public void setinputAreaText(String text)
	{
	    inputArea.setText(text);
	}
	
	public void sendUDPMessage(String messageSent)
	{
	    byte[] byteDatum = new byte[messageSent.length() + 1];//byteArrayDatum;
	    byteDatum = messageSent.getBytes();
	    InetAddress serverInetAddress = null;
	    DatagramPacket packetToBeSent = null;
	    DatagramSocket datagramSocket = null;
	    try
	    {
	        serverInetAddress = InetAddress.getByName(host);
	    } catch(UnknownHostException uhe)
	    {
	        this.appendMessageAreaText(EXCEPTION + "udp发送报文时出现未知主机异常,消息未发出");
	        return ;
	    }
	    packetToBeSent = new DatagramPacket(byteDatum, byteDatum.length, serverInetAddress, udpPort);
	    try
	    {
	        datagramSocket = new DatagramSocket();
	    } catch(SocketException se)
	    {
	        this.appendMessageAreaText(EXCEPTION + "无法打开DatagramSocket,消息未发出");
	        return ;
	    }
	    try
	    {
	        datagramSocket.send(packetToBeSent);
	    } catch(IOException ioe)
	    {
	        this.appendMessageAreaText(EXCEPTION +"Datagrampacket无法发出");
	        return ;
	    }
	}
	
	public void sendQuitMessage(String userName)
	{
	    sendUDPMessage("QUIT " + userName);
	}
	
	public void afterLogin()
	{
	        hasLogin = true;
	        //设置按钮为发送消息模式:
	        sendButton.setIcon(new ImageIcon(getClass().getResource("send.gif")));
	        //接收欢迎&udp端口消息 
	        udpPort = tcpConnection.getWelcomAndUDPPort();
	        //显示连接信息:
	        this.appendMessageAreaText(PROMPT + "成功登陆至服务器 " + udpPort + " UDP端口,欢迎进入本聊天室");
	        //保存用户名:
	        userName = inputArea.getText();
	        //修改窗口名称:
	        this.setTitle("别问我是谁,请与我面对——" + userName);
	        //将自己显示在用户列表中
	        lItems.add(0,userName);
	        //开始接收数据:
	        tcpConnection.start();
	}
	
	public void disConnect()
	{
	    //如果是没有连接或是已经断开连接,就返回
	    if (tcpConnection == null)
	    {
	        this.appendMessageAreaText(PROMPT + "连接已断开");
	        return ;
	    }
	    this.appendMessageAreaText(PROMPT + "正在断开连接...");
	    //先停止接收TCP消息
	    tcpConnection.stopThread();
	    //如果用户在没有登陆的时候就去断开连接,这时他的userName是不存在的:
	    if (userName != null)
	    {
	        //当用户退出时应该去除所有的在线用户信息:
	        lItems.removeAllElements();
	        //UDP向服务器报告退出消息:
	        sendQuitMessage(userName);
	    }
        tcpConnection.closeSocket();
        //只有在这里设置为null时,才可以重新连接:
        tcpConnection = null;//垃圾回收自动回收原来TCPConnection对象
        hasLogin = false;
        this.appendMessageAreaText(PROMPT + "连接断开!");
	}
	
	public void connectToServer()
	{
	    if (tcpConnection == null) {
	        this.appendMessageAreaText(PROMPT + "开始连接到 host:" + this.host + ",TCP port" + this.port);
            tcpConnection = new TCPConnection(this, host, port);
            if (PublicChatGUI.this.tcpConnection.connectSuccess == false)
            {
                this.appendMessageAreaText(ERROR + "连接不成功,请配置后重新连接");
                //生成的没有连接成功的TCPConnection对象由垃圾回收机制回收
                this.tcpConnection = null;
            } else
            {
                PublicChatGUI.this.appendMessageAreaText(PROMPT + "已连接到服务器!请在输入栏内输入用户名以登陆");
            }
        }
        else
            PublicChatGUI.this.appendMessageAreaText(PROMPT + "连接已经存在");
	}
	void initPanel()
	{
	    panel = new JPanel(new BorderLayout());
		    //panel包括communicationPanel和listPanel:
			JPanel communicationPanel = new JPanel(new GridLayout(2,1));
			JPanel listPanel = new JPanel(new BorderLayout());
		
		        //communicationPanel包括messagePanel和sendPanel
				JPanel messagePanel = new JPanel(new BorderLayout());
				JPanel sendPanel = new JPanel(new BorderLayout());
					//sendPanel包括inputPanel、toolbarPanel和buttonPanel
					JPanel toolbarPanel = new JPanel(new BorderLayout());
					JPanel inputPanel = new JPanel(new BorderLayout());
					JPanel buttonPanel = new JPanel(new GridLayout(1,2));
					
					
		//用于文本显示的方便,将文本区包装于滚动Panel中 
		JScrollPane messagePane = null;
		JScrollPane inputPane = null;
		//用户较多时,要将List置于一个ScrollPane中:
		JScrollPane listPane = null;
		
		if (messageArea == null)
		{
			messageArea = new JTextArea();
			messageArea.setLineWrap(true);
			messageArea.setEditable(false);
			this.appendMessageAreaText(PROMPT + "请选择\"系统\\建立连接\"以建立与服务器的TCP连接");
			messagePane = new JScrollPane(messageArea, 
					JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
					JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		}
		
		if (inputArea == null)
		{
			inputArea = new JTextArea();
			inputArea.setLineWrap(true);
			inputPane = new JScrollPane(inputArea, 
			JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
			JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		}
		
		if (toolBar == null)
		{
		    toolBar = new JToolBar();
		    //设置默认字样
		    fontStyle = messageArea.getFont().getStyle();
		    fontFamily = messageArea.getFont().getFamily();
		    fontSize = messageArea.getFont().getSize();
		    
		    font = new Font(fontFamily, fontStyle, fontSize);
		    
		    JComboBox fonts = new JComboBox();
		    String [] fontNames = GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames();
		    for(int i = 0; i < fontNames.length; i++)
		        fonts.addItem(fontNames[i]);
		    fonts.setToolTipText("修改字体");
		    fonts.setSelectedItem(fontFamily);
		    fonts.addActionListener(new ActionListener() {
		        public void actionPerformed(ActionEvent ae)
		        {
		            fontFamily = (String)(((JComboBox)ae.getSource()).getSelectedItem());
		            font = new Font(fontFamily, fontStyle, fontSize);
		            messageArea.setFont(font);
		            inputArea.setFont(font);
		        }
		    });
		    
		    JComboBox fontSizeChooser = new JComboBox();
		    for(int i = 8; i < 40; i++)
		        fontSizeChooser.addItem(String.valueOf(i));
		    fontSizeChooser.setToolTipText("字体大小");
		    fontSizeChooser.setSelectedItem(String.valueOf(fontSize));
		    fontSizeChooser.addActionListener(new ActionListener() {
		        public void actionPerformed(ActionEvent ae)
		        {
		            fontSize = Integer.parseInt((String)(((JComboBox)ae.getSource()).getSelectedItem()));
		            font = new Font(fontFamily, fontStyle, fontSize);
		            messageArea.setFont(font);
		            messageArea.setFont(font);
		        }
		    });
		    
		    JButton colorSet = new JButton(new ImageIcon(getClass().getResource("color.gif")));
		    colorSet.addActionListener(new ActionListener() {
		        public void actionPerformed(ActionEvent ae)
		        {
		            Color colorGot = JColorChooser.showDialog(PublicChatGUI.this, "颜色", Color.BLACK);
		            PublicChatGUI.this.messageArea.setForeground(colorGot);
		            PublicChatGUI.this.list.setForeground(colorGot);
		        }
		    });
		    colorSet.setToolTipText("颜色");
		    toolBar.add(colorSet);
		    toolBar.add(fonts);
		    toolBar.add(fontSizeChooser);
		}
		
		if (list == null)
		{
		    list = new JList(lItems);
		    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
			list.setFixedCellWidth(100);	
		    listPane = new JScrollPane(list,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		    list.addFocusListener(new FocusListener() {
		        public void focusLost(FocusEvent fe)
		        {
		            //如果是在消息显示去点击鼠标而导致的JList失去焦点,则表示用户取消选择:
		            if (messageArea == fe.getOppositeComponent())
		            {
		                list.clearSelection();
		                privateReceiver = (String) list.getSelectedValue();
		            }
		        }
		        public void focusGained(FocusEvent fe)
		        {
		            privateReceiver = (String) list.getSelectedValue();
		        }
		    });
		    list.addListSelectionListener(new ListSelectionListener() {
		        public void valueChanged(ListSelectionEvent lse)
		        {
		            privateReceiver = (String) list.getSelectedValue();
		        }
		    });
		}
		if (sendButton == null)
		{
			sendButton = new JButton(new ImageIcon(getClass().getResource("login.gif")));
			sendButton.setText("Alt + Enter");
			sendButton.setMnemonic(KeyEvent.VK_ENTER);
			sendButton.setToolTipText("Press Alt + Enter instead!");
			sendButton.addActionListener(new ActionListener() {
				boolean loginSuccess = false;
				public void actionPerformed(ActionEvent buttonEvent) {
				    if(PublicChatGUI.this.tcpConnection == null)
				    {
				        PublicChatGUI.this.appendMessageAreaText(ERROR + "尚未连接,请选择\"系统\\建立连接\"以建立与服务器的TCP连接");
				        return;
				    }
				    //未登录则进行登陆:

⌨️ 快捷键说明

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