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

📄 chatserver.java

📁 小小聊天室
💻 JAVA
字号:

import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import java.lang.*;
import java.util.*;
import java.io.*;
import java.net.*;
/**
 *聊天程序的服务器端
 **/
class ChatServer extends JFrame implements Runnable
{
	//控件的初始化
	JLabel lbSpace1=new JLabel("     ");
	JLabel lbSpace2=new JLabel("     ");
	JPanel p1 = new JPanel(new FlowLayout(FlowLayout.CENTER,10,5));
	JLabel lbport = new JLabel("请输入服务端口号:");
	JTextField tfport = new JTextField("8080   ");
	JButton btnstop = new JButton("停止服务");
	JPanel p2 = new JPanel(new BorderLayout());
	JTextPane tpcontent = new JTextPane();

	//JPanel p3 = new JPanel(new FlowLayout(FlowLayout.CENTER,10,5));
	JPanel p3 = new JPanel(new GridLayout());

	JButton btnsend = new JButton("发送至");
	JComboBox comclient = new JComboBox();
	JPanel p4 = new JPanel(new BorderLayout());
	JTextPane tplog = new JTextPane();
	JLabel lbstate = new JLabel("初始化");
	//初始化用于网络编程的变量
	public static int PORT = 8080;
	//public  static  boolean flag = true;
	public static String strlog = new String("");
	public static ServerSocket s;
	public java.util.List<Socket> sockList = new ArrayList();
	/**
	 *构造方法。初始化界面
	 **/
	ChatServer()throws IOException
	{
		super("小小聊天室-服务器端");
		Font ft = new Font("宋体",1,12);
		lbport.setFont(ft);
		lbport.setForeground(new Color(0,0,0));
		tfport.disable();
		tpcontent.setFont(ft);
		tplog.setFont(ft);
		p1.add(lbport);
		p1.add(tfport);
		btnstop.setFont(ft);
		tplog.disable();
		TitledBorder tb = new TitledBorder("需要发送的内容");
		tb.setTitleFont(ft);
		JScrollPane p6 = new JScrollPane(tpcontent);
		p6.setBorder(tb);
		p2.add(p1,BorderLayout.NORTH);
		p2.add(p6,BorderLayout.CENTER);
		p2.add(Box.createHorizontalStrut(20),BorderLayout.WEST);
		p2.add(Box.createHorizontalStrut(20),BorderLayout.EAST);

		btnsend.setFont(ft);
		btnsend.setVisible(true);
		btnsend.addActionListener(new SendListener());
		comclient.addActionListener(new SelectedListener());

		//comclient.setSize(new Dimension(60,20));//comclient.getHeight()
		//p3.add(btnsend);
		//p3.add(comclient);

		p3.add(lbSpace1);
		p3.add(btnsend);
		p3.add(comclient);
		p3.add(lbSpace2);

		p2.add(p3,BorderLayout.SOUTH);

		TitledBorder tb2 = new TitledBorder("日志");
		tb2.setTitleFont(ft);
		JScrollPane p5 = new JScrollPane(tplog);
		p5.setBorder(tb2);
		lbstate.setFont(ft);
		p4.add(Box.createHorizontalStrut(20),BorderLayout.WEST);
		p4.add(p5,BorderLayout.CENTER);
		p4.add(Box.createHorizontalStrut(20),BorderLayout.EAST);
		p4.add(lbstate,BorderLayout.SOUTH);
		//总体布局
		setLayout(new BoxLayout(this.getContentPane(),BoxLayout.Y_AXIS));
		add(p2);
		add(Box.createVerticalStrut(5));
		add(p4);

		//显示界面
		setSize(500,500);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		setVisible(true);
	}
	/**
	 *线程函数。不断的监听连接请求
	 **/
	public void run()
	{
		lbstate.setText("服务启动,端口为"+tfport.getText());
		 	try{
			    	while(true)
					{
						Socket sock = s.accept();
						new ServerRcvThread(sock);
					}
			}catch(IOException e)
			{
				System.out.println("UExpected Error!");
			}
	}
	/**
	 *主函数。首先初始化主套接字之后再初始化界面
	 **/
	public static void main(String[] args) throws IOException
	{
		try{
			s = new ServerSocket(PORT);
			ChatServer cs = new ChatServer();
			cs.run();
		}
		finally
		{
			s.close();
		}


	}
/**
 *"发送至"按钮的监听器。得到与用户选择的目的地址相对应的套接字,利用这个套接字开启一个
 *负责发送数据的线程
 **/
	class SendListener implements  ActionListener
	{
		 public synchronized void actionPerformed(ActionEvent e)
		 {
		 	int i = comclient.getSelectedIndex();
			if(i<0)return;
			Socket s = sockList.get(i);
			lbstate.setText("向"+(String)(comclient.getItemAt(i))+"发送");
			try
			{
				new ServerSendThread(s);
		 	}catch(IOException er)
		 	{
		 		er.printStackTrace();
		 	}
		 }
	}

	class SelectedListener implements  ActionListener
	{
		 public synchronized void actionPerformed(ActionEvent e)
		 {
		 	int i = comclient.getSelectedIndex();
			if(i<0)return;
			Socket s = sockList.get(i);
			lbstate.setText("向"+(String)(comclient.getItemAt(i))+"发送");
		 }
	}



	/**
	 *接收数据的线程类
	 **/
	class ServerRcvThread extends Thread
	{
		Socket sock;
		private InputStream in;
		/**
		 *构造方法。初始化本类的套接字,开启线程
		 **/
		ServerRcvThread(Socket s) throws IOException
		{
			sock = s;
			in = sock.getInputStream();
			start();
		}
		/**
		 *线程运行函数。将新的套接字加入到链表。并读取套接字的字符流显示出来
		 **/
		public void run()
		{
			try{
				byte[] infor = new byte[100];
				int len;
				String str = new String("");
				while(true)
				{
					if(!sockList.contains(sock))
					{
						sockList.add(sock);
						//str = "(IP = " + sock.getInetAddress() + ",PORT = " + sock.getPort() + ")";
						str = sock.getInetAddress() + ": " + sock.getPort();
						comclient.addItem(str);
					}
					else
					{
						//str = "(IP = " + sock.getInetAddress() + ",PORT = " + sock.getPort() + ")";
						str = sock.getInetAddress() + " :" + sock.getPort();
					}

					lbstate.setText("来自"+str+" ");
					len = in.read(infor);
					if(len != -1)
					{
						strlog += str + " 发送:\n";
						str = new String(infor,0,len);
						strlog += str + "\n";
						tplog.setText(strlog);
					}
				}
			}
			catch(IOException e)
			{
				System.out.println("接受错误!");
			}
		}
	}
	/**
	 *发送线程。负责发送数据
	 **/
	class ServerSendThread extends Thread
	{
		private Socket sock;
		private OutputStream os;
		/**
		 *构造方法。使用参数来初始化实例的套接字变量和输出流变量
		 **/
		ServerSendThread(Socket s)throws IOException
		{
			sock = s;
			os = sock.getOutputStream();
			start();
		}
		/**
		 *线程运行函数。发送数据
		 **/
		public void run()
		{
			String str = tpcontent.getText();

			try{
				os.write(str.getBytes());
				tpcontent.setText(new String(""));
			}catch(IOException e)
			{
				e.printStackTrace();
			}
		}
	}
}

⌨️ 快捷键说明

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