熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> Java核心技術 >> 正文

Java實現網絡監聽

2022-06-13   來源: Java核心技術 

  // tcpServerjava by fpont /
  
  // usage : java tcpServer
  // default port is
  // connection to be closed by client
  // this server handles only connection
  
  import *;
  import javaio*;
  
  public class tcpServer {
  
  public static void main(String args[]) {
  
  int port;
  ServerSocket server_socket;
  BufferedReader input;
  try {
  port = IntegerparseInt(args[]);
  }
  catch (Exception e) {
  Systemoutprintln(port = (default));
  port = ;
  }
  
  try {
  server_socket = new ServerSocket(port);
  Systemoutprintln(Server waiting for client on port +
  server_socketgetLocalPort());
  // server infinite loop
  while(true) {
  Socket socket = server_socketaccept();
  Systemoutprintln(New connection accepted +
  socketgetInetAddress() +
  : + socketgetPort());
  input = new BufferedReader(new InputStreamReader(socketgetInputStream()));
  // print received data
  try {
  while(true) {
  String message = inputreadLine();
  if (message==null) break;
  Systemoutprintln(message);
  }
  }
  catch (IOException e) {
  Systemoutprintln(e);
  }
  
  // connection closed by client
  try {
  socketclose();
  Systemoutprintln(Connection closed by client);
  }
  catch (IOException e) {
  Systemoutprintln(e);
  }
  }
  }
  catch (IOException e) {
  Systemoutprintln(e);
  }
  }
  }
  
  // tcpClientjava by fpont /
  
  // usage : java tcpClient
  // default port is
  
  import *;
  import javaio*;
  
  public class tcpClient {
  
  public static void main(String[] args) {
  
  int port = ;
  String server = localhost;
  Socket socket = null;
  String lineToBeSent;
  BufferedReader input;
  PrintWriter output;
  int ERROR = ;
  
  // read arguments
  if(argslength == ) {
  server = args[];
  try {
  port = IntegerparseInt(args[]);
  }
  catch (Exception e) {
  Systemoutprintln(server port = (default));
  port = ;
  }
  }
  
  // connect to server
  try {
  socket = new Socket(server port);
  Systemoutprintln(Connected with server +
  socketgetInetAddress() +
  : + socketgetPort());
  }
  catch (UnknownHostException e) {
  Systemoutprintln(e);
  Systemexit(ERROR);
  }
  catch (IOException e) {
  Systemoutprintln(e);
  Systemexit(ERROR);
  }
  
  try {
  input = new BufferedReader(new InputStreamReader(Systemin));
  output = new PrintWriter(socketgetOutputStream()true);
  
  // get user input and transmit it to server
  while(true) {
  lineToBeSent = inputreadLine();
  // stop if input line is
  if(lineToBeSentequals()) break;
  outputprintln(lineToBeSent);
  }
  }
  catch (IOException e) {
  Systemoutprintln(e);
  }
  
  try {
  socketclose();
  }
  catch (IOException e) {
  Systemoutprintln(e);
  }
  }
  }
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26703.html
    推薦文章
    Copyright © 2005-2022 電腦知識網 Computer Knowledge   All rights reserved.