/**
   * Connects to the remote machine by establishing a tunnel through a HTTP proxy with Basic
   * authentication. It issues a CONNECT request and authenticates with the HTTP proxy with Basic
   * protocol.
   *
   * @param address remote machine to connect to
   * @return a TCP/IP socket connected to the remote machine
   * @throws IOException if an I/O error occurs during handshake (a network problem)
   */
  private Socket authenticateBasic(InetSocketAddress address, ConnectivitySettings cs)
      throws IOException {
    Socket proxy = new Socket(cs.getProxyHost(), cs.getProxyPort());
    BufferedReader r =
        new BufferedReader(
            new InputStreamReader(new InterruptibleInputStream(proxy.getInputStream())));
    DataOutputStream dos = new DataOutputStream(proxy.getOutputStream());

    String username = cs.getProxyUsername() == null ? "" : cs.getProxyUsername();
    String password = cs.getProxyPassword() == null ? "" : String.valueOf(cs.getProxyPassword());
    String credentials = username + ":" + password;
    String basicCookie = Base64Encoder.encode(credentials.getBytes("US-ASCII"));

    dos.writeBytes("CONNECT ");
    dos.writeBytes(address.getHostName() + ":" + address.getPort());
    dos.writeBytes(" HTTP/1.0\r\n");
    dos.writeBytes("Connection: Keep-Alive\r\n");
    dos.writeBytes("Proxy-Authorization: Basic " + basicCookie + "\r\n");
    dos.writeBytes("\r\n");
    dos.flush();

    String line = r.readLine();
    if (sConnectionEstablishedPattern.matcher(line).find()) {
      for (; ; ) {
        line = r.readLine();
        if (line.length() == 0) break;
      }
      return proxy;
    }
    throw new IOException("Basic authentication failed: " + line);
  }
  private void receiveMessages() throws IOException {
    // handshake (true) endpoint versions
    DataOutputStream out = new DataOutputStream(socket.getOutputStream());
    // if this version is < the MS version the other node is trying
    // to connect with, the other node will disconnect
    out.writeInt(MessagingService.current_version);
    out.flush();
    DataInputStream in = new DataInputStream(socket.getInputStream());
    int maxVersion = in.readInt();
    // outbound side will reconnect if necessary to upgrade version
    assert version <= MessagingService.current_version;
    from = CompactEndpointSerializationHelper.deserialize(in);
    // record the (true) version of the endpoint
    MessagingService.instance().setVersion(from, maxVersion);
    logger.debug(
        "Set version for {} to {} (will use {})",
        from,
        maxVersion,
        MessagingService.instance().getVersion(from));

    if (compressed) {
      logger.debug("Upgrading incoming connection to be compressed");
      in = new DataInputStream(new SnappyInputStream(socket.getInputStream()));
    } else {
      in = new DataInputStream(new BufferedInputStream(socket.getInputStream(), 4096));
    }

    while (true) {
      MessagingService.validateMagic(in.readInt());
      receiveMessage(in, version);
    }
  }
  private void initialise(MinecraftServer minecraftServer) {
    Socket socket = new EmptySocket();
    NetworkManager conn = null;
    try {
      conn =
          new EmptyNetworkManager(
              socket,
              "npc mgr",
              new Connection() {
                @Override
                public boolean a() {
                  return false;
                }
              },
              server.F().getPrivate());
      playerConnection = new EmptyNetHandler(minecraftServer, conn, this);
      conn.a(playerConnection);
    } catch (IOException e) {
      // swallow
    }

    getNavigation().e(true);
    X = 1F; // stepHeight - must not stay as the default 0 (breaks steps).
    // Check the EntityPlayer constructor for the new name.

    try {
      socket.close();
    } catch (IOException ex) {
      // swallow
    }
  }
 public SocketWordRepresentation(TfIdf tfIdf, String host, int port, String cachePath)
     throws IOException {
   super(tfIdf, cachePath);
   this.socket = new Socket(host, port);
   this.out = new PrintWriter(socket.getOutputStream(), true);
   this.in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
 }
 private PDBTEW2Listener(PDBTExecSingleCltWrkInitSrv srv, Socket s) throws IOException {
   _srv = srv;
   _s = s;
   _ois = new ObjectInputStream(_s.getInputStream());
   _oos = new ObjectOutputStream(_s.getOutputStream());
   _oos.flush();
 }
Beispiel #6
0
  public static void main(String[] args) {
    if (args.length > 2) {
      System.out.println(
          "Usage: Floor Client <port> <hex>"); // 8000 3D0000330121000000005623000102033000
      System.exit(0);
    }
    String sPort = args[0];
    String sHex = args[1];

    try {
      // Connect to the server
      Socket socket = new Socket("localhost", Integer.valueOf(sPort));

      // Create Stream for output
      PrintStream out = new PrintStream(socket.getOutputStream());

      // Write into the socket a binary representation of the Hex string in order to simulate a
      // floor element.
      out.write(cUtils.hexStringToByteArray(sHex));

      // Close when done
      out.close();
      socket.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Beispiel #7
0
 @Override
 public void run() {
   try {
     ServerSocket ss = new ServerSocket(port);
     while (!interrupted()) {
       try (Socket s = ss.accept(); ) {
         InputStream in = s.getInputStream();
         OutputStream out = s.getOutputStream();
         ChannelLevelInputStream cin = new ChannelLevelInputStream(in);
         ChannelLevelPacket clp = cin.readPacket();
         PALInputStream pin = new PALInputStream(new ByteArrayInputStream(clp.getPacketData()));
         PALRequest req = pin.readRequest();
         PALResponse resp = process(req);
         ByteArrayOutputStream bout = new ByteArrayOutputStream();
         PALOutputStream pout = new PALOutputStream(bout);
         pout.writePALResponse(resp);
         ChannelLevelPacket packet =
             new ChannelLevelPacket(
                 clp.getAddressS(), clp.getAddressD(), 0x48, bout.toByteArray());
         ChannelLevelOutputStream cout = new ChannelLevelOutputStream(out);
         cout.writePacket(packet);
         cout.close();
         cin.close();
         pout.close();
         pin.close();
       } catch (IOException e) {
         e.printStackTrace();
       }
     }
     ss.close();
   } catch (IOException e1) {
     e1.printStackTrace();
     return;
   }
 }
 public void run() {
   try {
     ObjectInputStream oin = new ObjectInputStream(client.getInputStream());
     test = new testMessage((testMessage) oin.readObject());
     serverMain.textPane2.setText(
         serverMain.textPane2.getText() + (new Date()) + ":" + test.qq + "开始验证有无密保问题......\n");
     ObjectOutputStream oout = new ObjectOutputStream(client.getOutputStream());
     String returnQuestion = "select * from safeQuestion_" + test.qq + ";";
     ResultSet res_return = state2.executeQuery(returnQuestion);
     if (res_return.next()) {
       changed = 2;
       String text1 = res_return.getString("question");
       res_return.next();
       String text2 = res_return.getString("question");
       res_return.next();
       String text3 = res_return.getString("question");
       oout.writeObject(new safeQuestionOrAnswer(null, text1, text2, text3));
       oout.close();
       serverMain.textPane2.setText(serverMain.textPane2.getText() + test.qq + "有无密保问题!\n");
     } else {
       oout.writeObject(null);
       changed = 1;
       serverMain.textPane2.setText(serverMain.textPane2.getText() + test.qq + "无密保问题!\n");
     }
     client.close();
     state2.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Beispiel #9
0
  @Override
  public void run() {
    try {
      host = InetAddress.getLocalHost().getHostName();
      s = new Socket(host, SERVER_PORT);
      output = new PrintWriter(s.getOutputStream(), true);
      input = new Scanner(s.getInputStream());
      output.println(name);

      while (!s.isClosed()) {

        if (input.hasNext()) {
          String msg = input.nextLine();

          if (msg.contains("!%#&")) {
            String tmp = msg.substring(4);
            tmp = tmp.replace("[", "");
            tmp = tmp.replace("]", "");

            String[] users = tmp.split(", ");

            activelist.setListData(users);
          } else {
            history.append(msg + "\n");
          }
        }
      }
    } catch (IOException e) {
      System.out.println(e);
      JOptionPane.showMessageDialog(null, "Unable to connect to the server.");
      System.exit(0);
    }
  }
  public static void main(String args[]) {
    int myport = 9090;
    Socket s;
    ServerSocket ss;
    BufferedReader fromSoc, fromKbd;
    PrintStream toSoc;
    String line, msg;
    try {
      s = new Socket("169.254.63.10", 6016);
      System.out.println("enter line");
      System.out.println("connected");
      toSoc = new PrintStream(s.getOutputStream());

      toSoc.println(myport);
      String url =
          "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)}; DBQ=D://db.mdb; DriverID=22;READONLY=true;";

      Connection con = DriverManager.getConnection(url, "", "");
      Statement st = con.createStatement();
      String ip = "169.254.63.10";
      int port = 6016;
      String video = "rooney";

      st.executeUpdate(
          " insert into p3 values('" + ip + "' , '" + port + "' , '" + video + "' );  ");

      fun();

    } catch (Exception e) {

      System.out.println("exception" + e);
    }
  }
  static void fun() {
    PrintStream toSoc;

    try {
      ServerSocket f = new ServerSocket(9090);
      while (true) {
        Socket t = f.accept();
        BufferedReader fromSoc = new BufferedReader(new InputStreamReader(t.getInputStream()));
        String video = fromSoc.readLine();
        System.out.println(video);
        searcher obj = new searcher();
        boolean fs;
        fs = obj.search(video);
        if (fs == true) {
          System.out.println("stream will starts");
          toSoc = new PrintStream(t.getOutputStream());
          toSoc.println("stream starts");

        } else {
          toSoc = new PrintStream(t.getOutputStream());
          toSoc.println("sorry");
        }
      }

    } catch (Exception e) {
      System.out.println(e);
    }
  }
 public static void main(String[] args) throws Exception {
   int choice = 0;
   Socket server = new Socket("127.0.0.1", 1300);
   ObjectOutputStream out = new ObjectOutputStream(server.getOutputStream());
   ObjectInputStream in = new ObjectInputStream(server.getInputStream());
   Scanner scan = new Scanner(System.in);
   while (true) {
     System.out.println("::::::::::::::::::::::::::::::::MENU::::::::::::::::::::::::::::::::::");
     System.out.println("1.Arithmetic Operations\n2.Logical Operations\n3.FileLookUpOperations");
     System.out.println("Enter the choice:");
     choice = scan.nextInt();
     switch (choice) {
       case 1:
         out.writeObject(1);
         System.out.println(in.readObject());
         break;
       case 2:
         out.writeObject(2);
         System.out.println(in.readObject());
         break;
       case 3:
         out.writeObject(3);
         System.out.println(in.readObject());
         break;
       default:
         System.out.println("Invalid Option");
         break;
     }
   }
 }
Beispiel #13
0
  @Override
  public void run() {
    while (running) {
      try {
        Socket socket = connection.getSocket();
        if (!socket.isClosed()) {
          BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
          String line = in.readLine();
          while (running && line != null) {
            if (!StringUtils.isEmpty(line)) {
              if (line.startsWith("{\"config\":{")) {
                connection.setConfig(getInputMapper().readValue(line, Config.class));
                configAction(ConfigModifyAction.ConfigReceived, null);
              } else if (line.equals("1")) {
                // pilight stopping
                connection.getSocket().close();
                throw new IOException("Connection to pilight lost");
              } else {
                Status status = getInputMapper().readValue(line, Status.class);
                callback.messageReceived(connection, status);
              }
            }
            line = in.readLine();
          }
        }
      } catch (IOException e) {
        logger.error("Error in pilight listener thread", e);
      }

      // empty line received (socket closed) or pilight stopped, try to reconnect
      reconnect();
    }

    cleanup();
  }
Beispiel #14
0
  public void run() {
    try {
      DataInputStream in = new DataInputStream(sockd.getInputStream());
      DataOutputStream out = new DataOutputStream(sockd.getOutputStream());

      BufferedReader br = new BufferedReader(new InputStreamReader(in));
      BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(out));
      vdb.setBw(bw);

      String name;

      while ((name = br.readLine()) != null) {
        System.out.println("graph for " + name);
        vdb.buildGraph(name, max_depth, peers_only);
        vdb.convertGraph();
        System.out.println("graph for " + name + " is ready");
        break;
      }

      br.close();
      in.close();
      bw.close();
      out.close();

      sockd.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Beispiel #15
0
 private void dispatchEvents(LoggerContext lc) {
   try {
     socket.setSoTimeout(acceptConnectionTimeout);
     ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
     socket.setSoTimeout(0);
     addInfo(receiverId + "connection established");
     while (true) {
       ILoggingEvent event = (ILoggingEvent) ois.readObject();
       Logger remoteLogger = lc.getLogger(event.getLoggerName());
       if (remoteLogger.isEnabledFor(event.getLevel())) {
         remoteLogger.callAppenders(event);
       }
     }
   } catch (EOFException ex) {
     addInfo(receiverId + "end-of-stream detected");
   } catch (IOException ex) {
     addInfo(receiverId + "connection failed: " + ex);
   } catch (ClassNotFoundException ex) {
     addInfo(receiverId + "unknown event class: " + ex);
   } finally {
     CloseUtil.closeQuietly(socket);
     socket = null;
     addInfo(receiverId + "connection closed");
   }
 }
Beispiel #16
0
  public static void main(String[] args) throws UnknownHostException, IOException {
    Socket sock = new Socket("localhost", 1111);
    Scanner s = new Scanner(System.in);

    OutputStream out = sock.getOutputStream();
    InputStream in = sock.getInputStream();

    out.flush();
    byte[] buffer = new byte[1024];
    int n;
    String index = "";

    if ((n = in.read(buffer)) != -1) {
      System.out.println(new String(buffer, 0, n));
      String name = s.nextLine();
      out.write(name.getBytes());
    }
    while (true) {
      if ((n = in.read(buffer)) != -1) {

        if ((new String(buffer, 0, n)).equals("DONE")) {
          System.out.println("File uploaded successfully");
        } else {
          System.out.println(new String(buffer, 0, n));
          index = s.nextLine();
          out.write(index.getBytes());
          System.out.println(new String(buffer, 0, in.read(buffer)));
        }
      }
    }
  }
  public static void main(String[] args) throws MalformedURLException, IOException {
    String data = "";
    int i = 1000;
    // Collisions aus Textdatei lesen
    BufferedReader bw = new BufferedReader(new FileReader("Collisions.txt"));
    String line;
    while ((line = bw.readLine()) != null) {
      // TODO Stringbuilder verwenden
      // POST Daten erzeugen
      data +=
          URLEncoder.encode(line, "UTF-8")
              + "="
              + URLEncoder.encode(new Double(Math.random()).toString(), "UTF-8");
    }

    // Socket erzeugen
    String hostname = "test.com";
    int port = 80;
    InetAddress addr = InetAddress.getByName(hostname);
    Socket socket = new Socket(addr, port);
    while (i-- > 0) {
      // Header Senden
      String path = "/bla/index.php";
      BufferedWriter wr =
          new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8"));
      wr.write("POST " + path + " HTTP/1.0\r\n");
      wr.write("Content-Length: " + data.length() + "\r\n");
      wr.write("Content-Type: application/x-www-form-urlencoded\r\n");
      wr.write("\r\n");

      // Sende Daten
      wr.write(data);
      wr.flush();
    }
  }
  /** Handshake with the debuggee */
  void handshake(Socket s, long timeout) throws IOException {
    s.setSoTimeout((int) timeout);

    byte[] hello = "JDWP-Handshake".getBytes("UTF-8");
    s.getOutputStream().write(hello);

    byte[] b = new byte[hello.length];
    int received = 0;
    while (received < hello.length) {
      int n;
      try {
        n = s.getInputStream().read(b, received, hello.length - received);
      } catch (SocketTimeoutException x) {
        throw new IOException("handshake timeout");
      }
      if (n < 0) {
        s.close();
        throw new IOException("handshake failed - connection prematurally closed");
      }
      received += n;
    }
    for (int i = 0; i < hello.length; i++) {
      if (b[i] != hello[i]) {
        throw new IOException("handshake failed - unrecognized message from target VM");
      }
    }

    // disable read timeout
    s.setSoTimeout(0);
  }
Beispiel #19
0
    public void run() {
      try {
        // 读取客户端数据
        DataInputStream input = new DataInputStream(socket.getInputStream());
        String clientInputStr = input.readUTF(); // 这里要注意和客户端输出流的写方法对应,否则会抛 EOFException
        // 处理客户端数据
        System.out.println("客户端发过来的内容:" + clientInputStr);

        // 向客户端回复信息
        DataOutputStream out = new DataOutputStream(socket.getOutputStream());
        System.out.print("请输入:\t");
        // 发送键盘输入的一行
        String s = new BufferedReader(new InputStreamReader(System.in)).readLine();
        out.writeUTF(s);

        out.close();
        input.close();
      } catch (Exception e) {
        System.out.println("服务器 run 异常: " + e.getMessage());
      } finally {
        if (socket != null) {
          try {
            socket.close();
          } catch (Exception e) {
            socket = null;
            System.out.println("服务端 finally 异常:" + e.getMessage());
          }
        }
      }
    }
Beispiel #20
0
  public static ArrayList<Patient> getPatientList(Socket socket, ArrayList<Patient> patientList) {
    int id;
    String ic;
    String fname;
    String lname;
    int age;
    int cnumber;

    try {
      OutputStream output = socket.getOutputStream();
      DataOutputStream dos = new DataOutputStream(output);
      InputStream input = socket.getInputStream();
      DataInputStream dis = new DataInputStream(input);

      dos.writeInt(2);

      int numberOfPatients = dis.readInt();

      for (int i = 0; i < numberOfPatients; i++) {
        id = dis.readInt();
        ic = dis.readUTF();
        fname = dis.readUTF();
        lname = dis.readUTF();
        age = dis.readInt();
        cnumber = dis.readInt();

        patientList.add(new Patient(id, ic, fname, lname, age, cnumber));
      }

    } catch (IOException e) {
      System.out.println("Cannot get IO streams.");
    }

    return patientList;
  }
Beispiel #21
0
  public static void send(Socket sa, String data) throws IOException {
    byte[] content = data.getBytes();

    byte[] length = String.format("%04d", content.length).getBytes();

    byte[] buf = new byte[1024];
    int reslen;
    int rc;
    //  Bounce the message back.
    InputStream in = sa.getInputStream();
    OutputStream out = sa.getOutputStream();

    out.write(length);
    out.write(content);

    System.out.println("sent " + data.length() + " " + data);
    int to_read = 4; // 4 + greeting_size
    int read = 0;
    while (to_read > 0) {
      rc = in.read(buf, read, to_read);
      read += rc;
      to_read -= rc;
      System.out.println("read " + rc + " total_read " + read + " to_read " + to_read);
    }
    System.out.println(String.format("%02x %02x %02x %02x", buf[0], buf[1], buf[2], buf[3]));
    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    reslen = Integer.valueOf(new String(buf, 0, 4));

    in.read(buf, 0, reslen);
    System.out.println("recv " + reslen + " " + new String(buf, 0, reslen));
  }
Beispiel #22
0
  private static void getMedicineList(Socket socket) {
    int medicineID;
    String medicineName;
    String medicineUnit;
    double price;

    try {
      OutputStream output = socket.getOutputStream();
      DataOutputStream dos = new DataOutputStream(output);
      InputStream input = socket.getInputStream();
      DataInputStream dis = new DataInputStream(input);

      dos.writeInt(8);

      int numberOfMedicine = dis.readInt();

      for (int i = 0; i < numberOfMedicine; i++) {
        medicineID = dis.readInt();
        medicineName = dis.readUTF();
        medicineUnit = dis.readUTF();
        price = dis.readDouble();

        medicineList.add(new Medicine(medicineID, medicineName, medicineUnit, price));
      }

    } catch (IOException e) {
      System.out.println("Cannot get IO streams.");
    }
  }
Beispiel #23
0
  Client() {
    sc = new Scanner(new InputStreamReader(System.in));
    try {
      clientSocket = new Socket("localhost", 27015);
      System.out.println("Connected to server!");
      System.out.println("Enter your Nick: ");
      Scanner sc = new Scanner(new InputStreamReader(System.in));
      name = sc.nextLine();
    } catch (Exception ex) {
      System.out.println("Can't connect to server " + ex);
    }
    try {
      in = new DataInputStream(clientSocket.getInputStream());
      out = new DataOutputStream(clientSocket.getOutputStream());

      ClientReader reader = new ClientReader();
      reader.start();
      String str = "";
      while (!str.equals("exit")) {
        str = sc.nextLine();
        out.writeUTF(name + ": " + str);
      }
    } catch (Exception ex) {
      System.out.println("Err: " + ex);
    }
  }
  /** Processes a input request . */
  @Override
  public void processInput(Socket socket, Server server) {
    BufferedReader reader = null;
    PrintStream writer = null;
    try {
      // Get I/O streams from the socket.
      reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      writer = new PrintStream(socket.getOutputStream());

      // Read input from socket and process incrementally.
      String line;
      while ((line = reader.readLine()) != null) {
        handleInput(line, reader);
      }

    } catch (Exception ex) {
      LOG.error("", ex);
    } finally {
      if (reader != null) {
        try {
          reader.close();
        } catch (IOException ex) {
        }
      }
      if (socket != null) {
        try {
          socket.close();
        } catch (IOException ex) {
        }
      }
    }
  }
Beispiel #25
0
  public void ListenAndDo() {
    try {
      while (true) {

        in = new ObjectInputStream(new BufferedInputStream(sockt.getInputStream()));

        Packet message = (Packet) in.readObject();
        Log.outString("Packet received from server (opcode :" + message.getOpcode() + ")");

        if (message.getOpcode().equals(0x07)) break;

        TreatPacket(message);
        sleep(100);
      }
      Log.outTimed("Close connection with server");
      sockt.close();
    } catch (SocketTimeoutException ste) {
      Log.outTimed("Server connection timeout");
    } catch (EOFException e) {
      try {
        sockt.close();
      } catch (IOException e1) {
        this.interrupt();
      }
      this.interrupt();
    } catch (SocketException e) {
      this.interrupt();
    } catch (Exception e) {
      e.printStackTrace();
      this.interrupt();
    }
  }
Beispiel #26
0
  @Override
  public void run() {
    PrintWriter out = null;
    BufferedReader in = null;
    try {
      out = new PrintWriter(client.getOutputStream());
      in = new BufferedReader(new InputStreamReader(client.getInputStream()));

      String line;
      while ((line = in.readLine()) != null) {
        out.println(line);
        out.flush();
      }
    } catch (Exception e) {
      System.err.println(e);
    } finally {
      try {
        out.close();
        in.close();
        client.close();
      } catch (IOException ex) {
        System.err.println(ex);
      }
    }
  }
 /**
  * there is an issue with this method: if it is called often enough, the <CODE>
  * _s.sendUrgentData(0);</CODE> method that it invokes, will force the <CODE>_s</CODE> socket to
  * close on the other end, at least on Windows systems. This behavior is due to the fact that
  * OOB data handling is problematic since there are conflicting specifications in TCP.
  * Therefore, it is required that the method is not called with high frequency (see the <CODE>
  * PDBTExecSingleCltWrkInitSrv._CHECK_PERIOD_MSECS</CODE> flag in this file.)
  *
  * @return true iff the worker is available to accept work according to all evidence.
  */
 private synchronized boolean getAvailability() {
   boolean res = _isAvail && _s != null && _s.isClosed() == false;
   if (res && _OK2SendOOB) { // work-around the OOB data issue
     // last test using OOB sending of data
     try {
       _OK2SendOOB = false; // indicates should not send OOB data until set to true
       _s.sendUrgentData(0); // unfortunately, if this method is called often enough,
       // it will cause the socket to close???
       res = true;
     } catch (IOException e) {
       // e.printStackTrace();
       utils.Messenger.getInstance()
           .msg("PDBTExecSingleCltWrkInitSrv.getAvailability(): Socket has been closed", 0);
       res = false;
       _isAvail = false; // declare availability to false as well
       // try graceful exit
       try {
         _s.shutdownOutput();
         _s.close(); // Now we can close the Socket
       } catch (IOException e2) {
         // silently ignore
       }
     }
   }
   return res;
 }
Beispiel #28
0
 public static void startServer(int port) {
   ServerSocket ssock;
   // Socket sock;
   // DezactiveazaBonus bonus= new DezactiveazaBonus();
   // Thread b=new Thread(bonus);
   // b.start();
   try {
     ssock = new ServerSocket(port);
     while (true) {
       Socket esock = null;
       try {
         esock = ssock.accept();
         while (listEmpty()) yield();
         // System.out.println("A intrat in bucla");
         assignThread(esock);
       } catch (Exception e) {
         try {
           esock.close();
         } catch (Exception ec) {
         }
       }
       // System.out.println("A iesit din bucla");
     }
   } catch (IOException e) {
   }
 }
  public void run() {
    System.out.println("New Communication Thread Started");

    try {
      PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
      BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

      String inputLine;
      String[] inputTemp = new String[3];

      while ((inputLine = in.readLine()) != null) {
        System.out.println("Server: " + inputLine);

        out.println(inputLine);

        if (inputLine.equals("Bye.")) break;
      }

      out.close();
      in.close();
      clientSocket.close();
    } catch (IOException e) {
      System.err.println("Problem with Communication Server");
      System.exit(1);
    }
  }
  void applySocketParams(Socket s) {
    if (sendBuffer > 0) {
      try {
        s.setSendBufferSize(sendBuffer);
      } catch (SocketException e) {
        logger.error("error setting sendBuffer to " + sendBuffer, e);
      }
    }

    if (recvBuffer > 0) {
      try {
        s.setReceiveBufferSize(recvBuffer);
      } catch (SocketException e) {
        logger.error("error setting recvBuffer to " + recvBuffer, e);
      }
    }

    try {
      s.setTcpNoDelay(tcpNoDelay);
    } catch (SocketException e) {
      logger.error("error setting TcpNoDelay to " + tcpNoDelay, e);
    }

    try {
      s.setKeepAlive(keepAlive);
    } catch (SocketException e) {
      logger.error("error setting KeepAlive to " + keepAlive, e);
    }
  }