networkclienttest.java

来自「nanjing university cs 的java课件。 对新手很有用。付」· Java 代码 · 共 71 行

JAVA
71
字号
import java.net.*;
import java.io.*;

public class NetworkClientTest{
	public static void main(String[] args) {
		String host = "mes.nju.edu.cn";
		if(args.length > 0)
			host = args[0];
		int port = 110;
		if(args.length > 1)
			port = Integer.parseInt(args[1]);
		NetworkClient nwClient = new NetworkClient(host, port);
		nwClient.connect();
	}
}

class NetworkClient{
	private String host;
	private int port;
	
	public NetworkClient(String host, int port){
		this.host = host;
		this.port = port;	
	}
	
	public String getHost(){
		return this.host;
	}
	
	public int getPort(){
		return this.port;
	}
	
	public void connect(){
		try{
			Socket client = new Socket(host, port);
			handleConnection(client);
		}
		catch(UnknownHostException uhe){
			System.out.println("Unknown host: " + host);
			uhe.printStackTrace();
		}
		catch(IOException ioe){
			System.out.println("IOException: " + ioe);
			ioe.printStackTrace();
		}
	}
	
	void handleConnection(Socket client) throws IOException{
		PrintWriter out = SocketUtil.getPrintWriter(client);
		BufferedReader in = SocketUtil.getBufferedReader(client);
		System.out.println("<< " + in.readLine());
		out.println("USER uliyas");
		System.out.println(">> USER uliyas");
		System.out.println("<< " + in.readLine());
		out.println("PASS 1234");
		System.out.println(">> PASS 1234");
		System.out.println("<< " + in.readLine());
		client.close();
	}
}

class SocketUtil{
	public static BufferedReader getBufferedReader(Socket s) throws IOException{
		return new BufferedReader(new InputStreamReader(s.getInputStream()));
	}
	
	public static PrintWriter getPrintWriter(Socket s) throws IOException{
		return new PrintWriter(s.getOutputStream(), true);
	}
}

⌨️ 快捷键说明

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