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

📄 socketclient.java

📁 一个用java 编写的可以和多个人聊天的服务器
💻 JAVA
字号:
package chat.socket;

import chat.*;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
import javax.swing.event.*;

public class SocketClient extends BaseClient
{

	public static void main(String[] args) throws Exception
	{
		// Get user setting from file
		getUserSetting();
		SetUI();

		String userid = (args.length > 0 ? args[0] : "Guestlogin");
		String password = (args.length > 1 ? args[1] : "login");
		String host = (args.length > 2 ? args[2] : "localhost");		

		SocketClient sc = new SocketClient(userid, password, host);
		//f = new ClientMenu();/*"Chat Socket Client (" + userid + ")"*/
		/*f.getContentPane().add(sc, BorderLayout.CENTER);
		WindowListener wL = new WindowAdapter()
		{
			public void windowClosing(WindowEvent e)
			{
				//sc.broadcastRemovedUser(userid);
				e.getWindow().dispose();
				System.exit(0);
			}
		};
		f.addWindowListener(wL);
		f.pack();
		f.setVisible(true);*/
	}

	public SocketClient(String user, String password, String host) throws Exception
	{
		userid = user;
		try
		{
			server = new SocketStub(user, password, host);
			if (settings.history == true)
				displayHistory();

			ClientMenu f = new ClientMenu("Chat Socket Client (" + userid + ")");/*"Chat Socket Client (" + userid + ")"*/
			f.getContentPane().add(this, BorderLayout.CENTER);
			WindowListener wL = new WindowAdapter()
			{
				public void windowClosing(WindowEvent e)
				{
					try{
					server.broadcastRemovedUser(userid);
					saveUserSetting();
					e.getWindow().dispose();
					System.exit(0);
					}catch (Exception be){}
				}
			};
			f.addWindowListener(wL);
			f.pack();
			f.setVisible(true);
			//addUser(userid);
		}catch (Exception e)
		{
			 JOptionPane.showMessageDialog(this, e.getMessage(), "Logon Error", JOptionPane.ERROR_MESSAGE);
			System.exit(0);
		}

	}

	class SocketStub extends Thread implements ChatServer
	{
		protected ServerSocket serverSocket;

		protected Socket sendSocket;
		protected Socket receiveSocket;

		protected DataOutputStream outOutput;
		protected DataInputStream outInput;

		protected DataInputStream inInput;

		public SocketStub(String userid, String password, String host) throws IOException, LogonFailedException
		{
			serverSocket = new ServerSocket(0);
			setPriority(Thread.MAX_PRIORITY);
			start();
			performLogon(userid, password, host);
		}

		public void performLogon(String user, String password, String host) throws IOException, LogonFailedException
		{
			InputStream is;
			OutputStream os;

			InetAddress addr = InetAddress.getByName(host);
			sendSocket = new Socket(addr, SocketServer.PORT_NUMBER);
			is = sendSocket.getInputStream();
			outInput = new DataInputStream(is);
			os = sendSocket.getOutputStream();
			outOutput = new DataOutputStream(os);
			outOutput.writeUTF(user);
			outOutput.writeUTF(password);
			outOutput.writeInt(serverSocket.getLocalPort());
			int status = outInput.readInt();
			if (status == SocketServer.LOGON_FAILED)
			{
				throw new LogonFailedException("Invalid userid and/or password specified");
			}

		}

		public void run()
		{
			ChatMessage message;
			long timeValue;
			java.util.Date msgDate;
			String msgText,idText;
			try
			{
				initialize();
				while(true)
				{
					int type = inInput.readInt(); 
					if (type == SocketServer.SENT_MSG)
					{
						timeValue = inInput.readLong();
						msgText = inInput.readUTF();
						msgDate = new java.util.Date(timeValue);
						message = new ChatMessage(msgDate, msgText);
						displayMessage(message);
					}
					else if (type == SocketServer.SENT_USER)
					{
						idText = inInput.readUTF();
						addUser(idText);
					}
					else if (type == SocketServer.REMOVE_USER)
					{
						idText = inInput.readUTF();
						removeUser(idText);
					}					
					else if (type == SocketServer.CLEAR_USER)
					{
						clearUser();
					}
				}
			}catch (Exception ioe){};
		}

		protected void initialize() throws IOException
		{
			InetAddress sendaddr;
			InetAddress recvaddr;
			InputStream is;
			Socket s = serverSocket.accept();
			sendaddr = sendSocket.getInetAddress();
			recvaddr = s.getInetAddress();
			if (sendaddr.equals(recvaddr))
			{
				receiveSocket = s;
				is = receiveSocket.getInputStream();
				inInput = new DataInputStream(is);
			}
		}

		public void broadcastMessage(String message) throws IOException
		{
			outOutput.writeInt(SocketServer.INVOKE_BROADCAST);
			outOutput.writeUTF(message);
		}

		public void broadcastRemovedUser(String user) throws IOException
		{
			outOutput.writeInt(SocketServer.INVOKE_DISCONNECT);
			outOutput.writeUTF(user);
		}

		public ChatMessage[] getHistory() throws IOException
		{
			ChatMessage[] messages = null;

			int count;
			long timeValue;
			java.util.Date msgDate;
			String msgText;

			outOutput.writeInt(SocketServer.INVOKE_GET_HISTORY);
			count = outInput.readInt();
			messages = new ChatMessage[count];
			for (int i =0; i < count; i++)
			{
				timeValue = outInput.readLong();
				msgText = outInput.readUTF();
				msgDate = new java.util.Date(timeValue);
				messages[i] = new ChatMessage(msgDate, msgText);
			}
			return messages;
		}

		//Overwrite methods
		//public void addUser() throws Exception{}
		public String[] getUser() throws Exception
		{
			String[] users = null;
			String msgText;

			outOutput.writeInt(SocketServer.INVOKE_GET_USER);
			int count = outInput.readInt();
			users = new String[count];
			for (int i=0; i < count; i++)
			{
				msgText = outInput.readUTF();
				users[i] = msgText;
			} 
			return users;
		}
	}
}

⌨️ 快捷键说明

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