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

📄 client.java

📁 java实现的Socket通信程序
💻 JAVA
字号:
/**
 * 
 */
package component;

/**
 * @author Administrator
 *
 */
import java.io.*;
import java.net.*;
public class Client 
{
	private String host;
	private int port;
	public Client(String host,int port)
	{
		this.host=host;
		this.port=port;
		connect();
	}
	private void connect()  //链接方法
	{
		try
		{
			Socket connection;
			//连接到服务器的端口指定端口
			if(host.equals("localhost"))
				connection=new Socket(InetAddress.getLocalHost(),port);
			else
				connection=new Socket(InetAddress.getByName(host),port);
			//获得键盘输入流
			BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
			PrintWriter out = new PrintWriter(connection.getOutputStream(),true);
			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			System.out.println("服务器信息:"+in.readLine());
			System.out.println("服务器信息:"+in.readLine());
			System.out.print("请输入 > ");
			boolean done = false;
			while(!done)
			{
				//从键盘上读字符串
				String line = stdin.readLine();
				//写向服务器
				out.println(line);
				//如果读到bye结束循环
				if(line.equalsIgnoreCase("bye"))
					done = true;
				//从服务器读取字符串
				String info = in.readLine();
				//在客户端显示从服务器返回的字符串
				System.out.println("服务器信息:"+info);
				if(!done)
					System.out.print("请输入 > ");
			}
			connection.close();
			
		}
		catch(SecurityException e)
		{
			System.out.println("连接服务器时出现安全问题!");
		}
		catch(IOException e)
		{
			System.out.println("连接服务器时出现安全问题!");
		}
	}
}

⌨️ 快捷键说明

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