client.java
来自「java实现的Socket通信程序」· Java 代码 · 共 69 行
JAVA
69 行
/**
*
*/
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 + =
减小字号Ctrl + -
显示快捷键?