-
您的位置:首页 → 资讯 → 教你一招 → Java实现网络监听
Java实现网络监听
时间:2004/10/15 1:20:00来源:本站整理作者:蓝点我要评论(0)
-
// 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);
}
}
}
相关阅读
Windows错误代码大全 Windows错误代码查询激活windows有什么用Mac QQ和Windows QQ聊天记录怎么合并 Mac QQ和Windows QQ聊天记录Windows 10自动更新怎么关闭 如何关闭Windows 10自动更新windows 10 rs4快速预览版17017下载错误问题Win10秋季创意者更新16291更新了什么 win10 16291更新内容windows10秋季创意者更新时间 windows10秋季创意者更新内容kb3150513补丁更新了什么 Windows 10补丁kb3150513是什么
-
热门文章
电视盒子怎么看百度云迅雷9怎么关闭右侧 迅迅雷99.99下载不完怎么网易云音乐怎么上传歌
最新文章
2022支付宝万能福扫福微信迎新春状态怎么设
微信小老虎头像怎么设置 微信ID后面设置小老抖音压岁钱卡怎么获得2022 抖音压岁钱获取方微博隐私保护怎么设置 微博隐私保护功能完善今日头条2022年集卡活动开启时间 今日头条2
人气排行
智学网怎么登录 智学网怎么查分数 智学网统教你怎么写电子邮箱格式?以163和QQ邮箱为例腾讯大王卡用了后悔怎么办 腾讯大王卡值得办缺少或丢失xinput1_3.dll解决方法,xinput1应用程序无法正常启动0xc000007b解决方法快播关闭怎么办?快播不能用了怎么看片将pdf文件转换为word文件的最简单方法如何破解QQ空间密码和权限
查看所有0条评论>>