📄 echoclient.java
字号:
//: c15:JabberClient.java
// From 'Thinking in Java, 2nd ed.' by Bruce Eckel
// www.BruceEckel.com. See copyright notice in CopyRight.txt.
// Very simple client that just sends
// lines to the server and reads lines
// that the server sends.
/*
C/S客户端应用
程序功能:完成C/S架构的客户端访问程序,访问服务端的8080端口,自身输出端口由系统自动分配一个1024以上的闲置端口.
作用:向服务发送请求,接收服务端返回数据.并输出显示
原理:首先解析服务端IP地址,通过服务端地址建立Socket实例,并通过该实例发送请求,和接收反射信息.
*/
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
public class EchoClient {
public static void main(String[] args) throws IOException {
// Passing null to getByName() produces the
// special "Local Loopback" IP address, for
// testing on one machine w/o a network:
InetAddress addr; //Java内部类解析IP地址
if (args.length >= 1) {
addr = InetAddress.getByName(args[0]); //从调用参数中获得服务端IP
} else {
addr = InetAddress.getByName(null); //如果没有参数则默认为本机IP
}
// Alternatively, you can use
// the address or name:
// InetAddress addr =
// InetAddress.getByName("127.0.0.1");
// InetAddress addr =
// InetAddress.getByName("localhost");
System.out.println("addr = " + addr);
Socket socket = new Socket(addr, EchoServer.PORT); //通过服务端地址和服务端口建立Socket实例
// Guard everything in a try-finally to make
// sure that the socket is closed:
try {
System.out.println("socket = " + socket);
BufferedReader in =
new BufferedReader(
new InputStreamReader(socket.getInputStream())); //建立输入流实例,转换字节流到字符流
// Output is automatically flushed
// by PrintWriter:
PrintWriter out =
new PrintWriter(
new BufferedWriter( //设置状态实时响应 "true"
new OutputStreamWriter(socket.getOutputStream())),true); //建立输出流实例,转换字符流到字节流
BufferedReader input =
new BufferedReader(new InputStreamReader(System.in)); //建立从键盘输入流实例
while (true) {
String str = input.readLine(); //由键盘数据
out.println(str); //输出到端口,并发送给服务端
if (str.equals("END")) //END进程结束
break;
String strSocket = in.readLine(); //接收返回信息
System.out.println(strSocket); //屏幕输出返回信息
}
/* for(int i = 0; i < 10; i ++) {
out.println("howdy " + i);
String str = in.readLine();
System.out.println(str);
}
out.println("END"); */
} finally {
System.out.println("closing...");
socket.close(); //关闭端口对象
}
}
} ///:~
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -