java 网络监听_java实现网络监听

import java.net.*;

import java.io.*;

public class tcpServer {

public static void main(String args[]) {

int port;

ServerSocket server_socket;

BufferedReader input;

try {

port = Integer.parseInt(args[0]);

}

catch (Exception e) {

System.out.println("port = 1500 (default)");

port = 1500;

}

try {

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);

}

// connection closed by client

try {

socket.close();

System.out.println("Connection closed by client");

}

catch (IOException e) {

System.out.println(e);

}

}

}

catch (IOException e) {

System.out.println(e);

}

}

}

import java.net.*;

import java.io.*;

public class tcpClient {

public static void main(String[] args) {

int port = 1500;

String server = "localhost";

Socket socket = null;

String lineToBeSent;

BufferedReader input;

PrintWriter output;

int ERROR = 1;

// read arguments

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;

}

}

// connect to server

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);

}

try {

input = new BufferedReader(new InputStreamReader(System.in));

output = new PrintWriter(socket.getOutputStream(),true);

// get user input and transmit it to server

while(true) {

lineToBeSent = input.readLine();

// stop if input line is "."

if(lineToBeSent.equals(".")) break;

output.println(lineToBeSent);

}

}

catch (IOException e) {

System.out.println(e);

}

try {

socket.close();

}

catch (IOException e) {

System.out.println(e);

}

}

}

版权声明:本文为博主原创文章,未经博主允许不得转载。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值