⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 clientconnect.java

📁 javaservice在windows制作服务程序
💻 JAVA
字号:
import java.io.*;import java.net.*;public class clientConnect {  protected String hostname;  private Socket socket;  protected int port;  PrintWriter logOut;  public clientConnect(String host, int port) {      this.hostname = host;      this.port = port;  }  public clientConnect(int port) {      this(null,port);  }  public void setLogStream(PrintWriter out) {this.logOut = out;}  public static void main(String[] args) {      if (args.length != 2 ) throw new IllegalArgumentException("参数数目不正确!");      int port = Integer.valueOf(args[1]).intValue();      String hostname = args[0];      clientConnect client = new clientConnect(hostname,port);      client.connectServer();  }  public void connectServer() {      try {          BufferedReader from_user = new BufferedReader(new InputStreamReader(System.in));          final PrintWriter to_user = new PrintWriter(System.out, true);          to_user.println("系统正在与服务器建立连接......");          if (this.hostname == null) socket = new Socket(InetAddress.getLocalHost(),port);          else socket = new Socket(this.hostname, port);//          socket.setSoTimeout(3000);          final Reader from_server = new InputStreamReader(socket.getInputStream());          PrintWriter to_server = new PrintWriter(socket.getOutputStream());          to_user.println("系统已经连接到" + socket.getInetAddress() +" : " + socket.getPort());          Thread t = new Thread() {          public void run() {              char[] buffer = new char[4096];              int chars_read;              try {                  while ((chars_read = from_server.read(buffer)) != -1) {                                            	  String tempString = new String(buffer,0,chars_read);                          to_user.println(tempString);                          to_user.flush();                  }              } catch(IOException e) {to_user.println(e);}              to_user.println("服务器已经关闭连接。");              System.exit(0);          }          };          t.setPriority(Thread.currentThread().getPriority()+1);          t.start();          String line;          while ((line = from_user.readLine()) != null) {              if (line.equals("exit")) break;              to_server.print(line + "\n");              to_server.flush();          }          socket.close();          to_user.println("客户端关闭连接。");          System.exit(0);      } catch (Exception e) {            System.err.print(e + "\n");            System.err.println("Usage: java clientConnect <hostname> <port>");      }  }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -