tcpclienttest.java

来自「《Java程序设计与应用》-张仕斌-源程序 《Java程序设计与应用》-张仕斌」· Java 代码 · 共 55 行

JAVA
55
字号
//TCPClientTest.java
import java.io.*;
import java.net.*;

public class TCPClientTest {
	public static void main(String[]args) {
		Socket clientSocket = null;      //通信套接字
		BufferedReader is = null;        //读对象
		DataOutputStream  os = null;     //写对象
		BufferedReader stdin = new BufferedReader(
		     new InputStreamReader(System.in)); //标准输入,用于接收输入
		String userInput,output;         //用户输入和从服务器收到的应答
		String server = "localhost";     //服务器名称
		int PORT = 6543;                 //服务器的监听端口
		
		if (args.length > 1) {   //要指定服务名和端口
			server = args[0];
			try {
				PORT = Integer.parseInt(args[1]);
			}catch(Exception e) {}
		}
		
		try {
			clientSocket = new Socket(server , PORT);  //创建连接套接字
			is = new BufferedReader(new InputStreamReader(
								clientSocket.getInputStream())); //获得读对象
			os = new DataOutputStream(clientSocket.getOutputStream()); //写对象
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		try { 
			System.out.print("Enter a string:");
			userInput = stdin.readLine();         //接收用户的键盘输入
			os.writeBytes(userInput + "\n");      //发送输入内容
		}catch(IOException e) {
			e.printStackTrace();
		}
		
		try {
			output = is.readLine();              //接收服务器的应答信息
			System.out.println("Information from Server: " + output); //输出
		}catch(IOException e) {
			e.printStackTrace();
		}
		
		try {
			is.close();
			os.close();
			clientSocket.close();
		}catch(IOException e) {
			e.printStackTrace();
		}
	}
}

⌨️ 快捷键说明

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