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

📄 connection.java

📁 C/S模型
💻 JAVA
字号:
import java.io.*;
import java.net.*;
class Connection extends Thread  
{
	protected Socket netClient;  //为客户端准备socket对象
	protected BufferedReader fromClient;  //处理从客户到服务器的数据转移
	protected PrintStream toClient;  //处理从服务器到客户的数据转移

	public Connection(Socket client) //这个参数用来传递客户的socket对象,实现服务器程序的多线程
	{
		netClient =client;
		try
		{
			//实现I/O
			fromClient=new BufferedReader(new InputStreamReader(netClient.getInputStream()));
			toClient=new PrintStream(netClient.getOutputStream());
		}
		catch (IOException e)
		{
			try
			{
				netClient.close();  //不关闭的话很快会消耗尽服务器资源
			}
			catch(IOException e1)
			{
				System.err.println("Unable to set up streams"+e1);
				return;
			}
		}
		this.start();  //启动线程
	}
	public void run()
	{
		String login,password;
		try
		{
			for (; ; )
			{
				//提示和读入用户
				toClient.println("Login: "); //往套接字写
				login=fromClient.readLine();
				if (login.equals("Billy"))
					System.out.println("From:"+netClient.getInetAddress().getHostAddress()+">有这个用户");					
				else
					{		
					System.out.println("From:"+netClient.getInetAddress().getHostAddress()+">没有这个用户");
					continue;
					}
					

				//提示和读入口令
				toClient.println("Password: "); //往套接字写
				password=fromClient.readLine(); //从套接字读
				if (password.equals("aaa"))
					System.out.println("From:"+netClient.getInetAddress().getHostAddress()+">密码正确");
				else
					{	
					System.out.println("From:"+netClient.getInetAddress().getHostAddress()+">密码错误");
					continue;
					}
				//检查用户和口令的语句块
				

				//如果用户被核准,通知客户
					toClient.println("Welcome!!");
				//接下来操作的语句块

			}
		}
		catch(IOException e)
		{
		}
		finally
		{
			try
			{
				netClient.close();
			}
			catch(IOException e)
			{}
		}
	}
}

⌨️ 快捷键说明

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