📄 tcpclient.java
字号:
import java.io.*;
import java.net.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TCPClient {
public static String IP_ADDRESS;
public static int COMM_PORT;
private Socket socket;
private final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSS");
private int count = 0;
private final int times = 3;
private final int interval = 60 * 1000 / 60;
private BufferedReader keyin = new BufferedReader(new InputStreamReader(System.in));
private BufferedReader is;
private PrintWriter os;
private String data;
public TCPClient() {
try {
do {
if(count++ == times) break;
} while(!connect());
if(socket != null) {
is = new BufferedReader(new InputStreamReader(socket.getInputStream()));
os = new PrintWriter(socket.getOutputStream());
while(true) {
Date dateTime = new Date();
System.out.print(dateFormat.format(dateTime.getTime()) + " Client>");
data = keyin.readLine();
if(data.equals("quit")) break;
send(data);
System.out.println(is.readLine());
}
socket.close();
}
else {
System.out.println("Connection refuse...");
}
}
catch(IOException ex) {
System.err.println("InterruptedException: " + ex.getMessage());
}
}
public boolean connect() {
try {
socket = new Socket(IP_ADDRESS, COMM_PORT);
System.out.println();
}
catch(UnknownHostException e) {
return delay();
}
catch(IOException e) {
return delay();
}
return true;
}
public boolean delay() {
System.out.print(count + " ");
try {
Thread.sleep(interval);
}
catch(InterruptedException ex) {
System.err.println("InterruptedException: " + ex.getMessage());
}
return false;
}
public void send(String msg) {
os.println(msg);
os.flush();
}
public static void main(String[] args) {
if(args[0].equals("")) args[0] = "127.0.0.1";
if(args[1].equals("")) args[1] = "2048";
IP_ADDRESS = args[0];
COMM_PORT = new Integer(args[1]);
TCPClient tcpClient = new TCPClient();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -