加入收藏 | 设为首页 | 会员中心 | 我要投稿 西双版纳站长网 (https://www.0691zz.com.cn/)- 数据计算、IT业界、服务器、教程、云日志!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

Java实现网络监听

发布时间:2019-12-12 08:08:13 所属栏目:MsSql教程 来源:蓝点
导读:// tcpServer.java by fpont 3/2000 . // default port is 1500. // connection to be closed by client. // this server handles only 1 connection. import java.io.*; ServerSocket server_socket; BufferedReader input; try { port = Integer.parseInt
// tcpServer.java by fpont 3/2000
.
// default port is 1500.
// connection to be closed by client.
// this server handles only 1 connection. import java.io.*; ServerSocket server_socket;
BufferedReader input;
try {
port = Integer.parseInt(args[0]);
}
catch (Exception e) {
System.out.println("port = 1500 (default)");
port = 1500;
} server_socket = new ServerSocket(port);
System.out.println("Server waiting for client on port " +
server_socket.getLocalPort());
// server infinite loop
while(true) {
Socket socket = server_socket.accept();
System.out.println("New connection accepted " +
socket.getInetAddress() +
":" + socket.getPort());
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// print received data
try {
while(true) {
String message = input.readLine();
if (message==null) break;
System.out.println(message);
}
}
catch (IOException e) {
System.out.println(e);
}
try {
socket.close();
System.out.println("Connection closed by client");
}
catch (IOException e) {
System.out.println(e);
}
}
}
catch (IOException e) {
System.out.println(e);
}
}
}
// default port is 1500 import java.io.*; String server = "localhost";
Socket socket = null;
String lineToBeSent;
BufferedReader input;
PrintWriter output;
int ERROR = 1;
if(args.length == 2) {
server = args[0];
try {
port = Integer.parseInt(args[1]);
}
catch (Exception e) {
System.out.println("server port = 1000 (default)");
port = 1500;
}
} try {
socket = new Socket(server, port);
System.out.println("Connected with server " +
socket.getInetAddress() +
":" + socket.getPort());
}
catch (UnknownHostException e) {
System.out.println(e);
System.exit(ERROR);
}
catch (IOException e) {
System.out.println(e);
System.exit(ERROR);
} input = new BufferedReader(new InputStreamReader(System.in));
output = new PrintWriter(socket.getOutputStream(),true);
while(true) {
lineToBeSent = input.readLine();
// stop if input line is "."
if(lineToBeSent.equals(".")) break;
output.println(lineToBeSent);
}
}
catch (IOException e) {
System.out.println(e);
} socket.close();
}
catch (IOException e) {
System.out.println(e);
}
}
}

(编辑:西双版纳站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读