コード例 #1
1
  /**
   * 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);
  }
コード例 #2
0
ファイル: F.java プロジェクト: ballon/hz
  public static void main(String[] args) throws IOException, InterruptedException {
    for (int iter = 1; iter <= 1000; ++iter) {
      System.out.println("HELLO");

      // ask for a value
      Socket s1 = new Socket("127.0.0.1", 12345);
      PrintWriter out = new PrintWriter(s1.getOutputStream(), true);
      BufferedReader in = new BufferedReader(new InputStreamReader(s1.getInputStream()));
      out.println(-1);
      String response = in.readLine();
      s1.close();
      out.close();
      in.close();

      // increase by 1
      int val = Integer.parseInt(response);
      val++;

      // set value
      Socket s2 = new Socket("127.0.0.1", 12345);
      out = new PrintWriter(s2.getOutputStream(), true);
      in = new BufferedReader(new InputStreamReader(s2.getInputStream()));
      out.println(val);
      s2.close();
      out.close();
      in.close();
    }
  }
コード例 #3
0
  /** Implement the run() method for the thread */
  public void run() {
    try {
      // Create data input and output streams
      DataInputStream fromPlayer1 = new DataInputStream(player1.getInputStream());
      DataOutputStream toPlayer1 = new DataOutputStream(player1.getOutputStream());
      DataInputStream fromPlayer2 = new DataInputStream(player2.getInputStream());
      DataOutputStream toPlayer2 = new DataOutputStream(player2.getOutputStream());

      // Write anything to notify player 1 to start
      // This is just to let player 1 know to start
      toPlayer1.writeInt(1);

      // Continuously serve the players and determine and report
      // the game status to the players
      while (true) {
        // Receive a move from player 1
        int row = fromPlayer1.readInt();
        int column = fromPlayer1.readInt();
        int yCoordinate = game.insert("[X]", column);

        // Check if Player 1 wins
        if (game.isWinner(column, yCoordinate, "[X]")) { // if a  winner is found
          toPlayer1.writeInt(PLAYER1_WON);
          toPlayer2.writeInt(PLAYER1_WON);
          sendMove(toPlayer2, row, column);
          break; // Break the loop
        } else {
          toPlayer2.writeInt(CONTINUE);
          sendMove(toPlayer2, row, column);
        }
        // Receive a move from Player 2
        row = fromPlayer2.readInt();
        column = fromPlayer2.readInt();
        yCoordinate = game.insert("[O]", column);
        // Check if Player 2 wins
        if (game.isWinner(column, yCoordinate, "[O]")) { // if a  winner is found
          toPlayer1.writeInt(PLAYER2_WON);
          toPlayer2.writeInt(PLAYER2_WON);
          sendMove(toPlayer1, row, column);
          break; // Break the loop
        } else if (game.boardIsFull()) { // Check if all cells are filled
          toPlayer1.writeInt(DRAW);
          toPlayer2.writeInt(DRAW);
          sendMove(toPlayer1, row, column);
          break;
        } else {
          // Notify player 2 to take the turn
          toPlayer1.writeInt(CONTINUE);
          // Send player 1's selected row and column to player 2
          sendMove(toPlayer1, row, column);
        }
      }
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
コード例 #4
0
  public void open() {
    try {
      streamIn = new DataInputStream(socket.getInputStream());
      streamInObject = new ObjectInputStream(socket.getInputStream());

    } catch (IOException ioe) {
      System.out.println("Error getting input stream: " + ioe);
      client.stop();
    }
  }
コード例 #5
0
ファイル: TestBase.java プロジェクト: liuxing9848/pokerth
 public PokerTHMessage receiveMessage(Socket s) throws Exception {
   byte[] header = new byte[4];
   s.getInputStream().read(header);
   int size = 0;
   for (int i = 0; i < 4; i++) {
     size <<= 8;
     size |= (int) header[i];
   }
   byte[] data = new byte[size];
   s.getInputStream().read(data);
   return PokerTHMessage.parseFrom(data);
 }
コード例 #6
0
ファイル: V4ServerV6Client.java プロジェクト: sopita/Cours
  public static void main(String[] args) {
    String ipv4;
    try {
      System.out.println("Stablishing the server socket...");
      ServerSocket srvSock = new ServerSocket(4201);
      System.out.println(
          "Server socket stablished to "
              + srvSock.getInetAddress().getHostName()
              + " at port number "
              + srvSock.getLocalPort()
              + ".\n");

      try {
        Socket comSock = srvSock.accept();
        System.out.println(
            "New connection stablished with "
                + comSock.getInetAddress().getHostName()
                + " (port "
                + comSock.getPort()
                + "), trying to communicate...");
        // DO STUFF
        try {
          BufferedReader br = new BufferedReader(new InputStreamReader(comSock.getInputStream()));
          ipv4 = br.readLine();
          br.close();
          comSock.close();
          srvSock.close();
          Socket sock = new Socket(ipv4, 4202);
          BufferedReader br2 = new BufferedReader(new InputStreamReader(sock.getInputStream()));
          System.out.println(br2.readLine());
          br2.close();
          sock.close();
          // System.out.println(ipv4);
        } catch (Exception e) {
          e.printStackTrace();
          System.out.println("Connection failed. Try again later.");
        }

      } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Problem with client.\n");
      }

    } catch (Exception e) {
      System.out.println("Failed to create server socket:");
      e.printStackTrace();
    }
  }
コード例 #7
0
  // **********************************************************************************
  //
  // Theoretically, you shouldn't have to alter anything below this point in this file
  //      unless you want to change the color of your agent
  //
  // **********************************************************************************
  public void getConnected(String args[]) {
    try {
      // initial connection
      int port = 3000 + Integer.parseInt(args[1]);
      s = new Socket(args[0], port);
      sout = new PrintWriter(s.getOutputStream(), true);
      sin = new BufferedReader(new InputStreamReader(s.getInputStream()));

      // read in the map of the world
      numNodes = Integer.parseInt(sin.readLine());
      int i, j;
      for (i = 0; i < numNodes; i++) {
        world[i] = new node();
        String[] buf = sin.readLine().split(" ");
        world[i].posx = Double.valueOf(buf[0]);
        world[i].posy = Double.valueOf(buf[1]);
        world[i].numLinks = Integer.parseInt(buf[2]);
        // System.out.println(world[i].posx + ", " + world[i].posy);
        for (j = 0; j < 4; j++) {
          if (j < world[i].numLinks) {
            world[i].links[j] = Integer.parseInt(buf[3 + j]);
            // System.out.println("Linked to: " + world[i].links[j]);
          } else world[i].links[j] = -1;
        }
      }
      currentNode = Integer.parseInt(sin.readLine());

      String myinfo =
          args[2] + "\n" + "0.7 0.45 0.45\n"; // name + rgb values; i think this is color is pink
      // send the agents name and color
      sout.println(myinfo);
    } catch (IOException e) {
      System.out.println(e);
    }
  }
コード例 #8
0
  public static void main(String[] args) {

    try {
      System.out.println("Creando socket servidor");

      ServerSocket serverSocket = new ServerSocket();

      System.out.println("Realizando el enlace");
      InetSocketAddress addr = new InetSocketAddress("localhost", 5555);
      serverSocket.bind(addr);

      System.out.println("Aceptando conexiones");
      Socket newSocket = serverSocket.accept();
      System.out.println("Conexión recibida");

      InputStream is = newSocket.getInputStream();
      OutputStream os = newSocket.getOutputStream();

      byte[] mensaje = new byte[25];
      is.read(mensaje);

      System.out.println("Mensaje recibido: " + new String(mensaje));
      System.out.println("Cerrando el nuevo socket");

      newSocket.close();

      System.out.println("Cerrando el socket servidor");
      serverSocket.close();

      System.out.println("Terminado");

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
コード例 #9
0
ファイル: TestTCPClient.java プロジェクト: shawtung/Startup
  public static void main(String[] args) {
    try {
      Socket s1 = new Socket("127.0.0.1", 57643);

      InputStream is = s1.getInputStream();
      DataInputStream dis = new DataInputStream(is);
      System.out.println(dis.readUTF());

      OutputStream os = s1.getOutputStream();
      DataOutputStream dos = new DataOutputStream(os);
      dos.writeUTF("Oh my gosh...");

      dis.close();
      is.close();
      dos.close();
      os.close();

      s1.close();
    } catch (ConnectException connExc) {
      connExc.printStackTrace();
      System.out.println("Server connection failed");
    } catch (IOException ioExc) {
      ioExc.printStackTrace();
    }
  }
コード例 #10
0
ファイル: Server.java プロジェクト: vicent216/QQ
 public void run() {
   try {
     boolean connected = true;
     System.out.println("a client has connected!");
     dis = new DataInputStream(s.getInputStream());
     dos = new DataOutputStream(s.getOutputStream());
     while (connected) {
       int cid = clients.indexOf(this) + 1;
       try {
         String str = dis.readUTF();
         System.out.println(str);
         for (int i = 0; i < clients.size(); i++) {
           clients.get(i).dos.writeUTF("Client" + cid + ":" + str);
         }
       } catch (IOException e) {
         connected = false;
       }
     }
     dis.close();
     dos.close();
     s.close();
     clients.remove(this);
     System.out.println("a client is qiut!");
   } catch (IOException e) {
     e.printStackTrace();
   }
 }
コード例 #11
0
ファイル: Nurse.java プロジェクト: benghan95/clinicassistant
  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.");
    }
  }
コード例 #12
0
  private void server() {
    new CountDown(60).start();
    while (true) {
      try {
        Socket socket = serverSock.accept();
        System.out.println("New Client:" + socket);
        if (readyState[6] == 1) {
          System.out.println("正在游戏中,无法加入");
          continue;
        }
        for (i = 0; i <= 5; i++) {
          if (players[i].equals("虚位以待")) break;
        }
        if (i > 5) {
          System.out.println("房间已满,无法加入");
          continue;
        }
        i++;
        ObjectOutputStream remoteOut = new ObjectOutputStream(socket.getOutputStream());
        clients.addElement(remoteOut);

        ObjectInputStream remoteIn = new ObjectInputStream(socket.getInputStream());
        new ServerHelder(remoteIn, remoteOut, socket.getPort(), i).start();
      } catch (IOException e) {
        System.out.println(e.getMessage() + ": Failed to connect to client.");
        try {
          serverSock.close();
        } catch (IOException x) {
          System.out.println(e.getMessage() + ": Failed to close server socket.");
        }
      }
    }
  }
コード例 #13
0
  /** 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);
  }
コード例 #14
0
ファイル: DaytimeClient.java プロジェクト: git263/letscode
  public static void main(String[] args) {

    String hostname;

    if (args.length > 0) {
      hostname = args[0];
    } else {
      hostname = "tock.usno.navy.mil";
    }

    try {
      Socket theSocket = new Socket(hostname, 13);
      InputStream timeStream = theSocket.getInputStream();
      StringBuffer time = new StringBuffer();
      int c;
      while ((c = timeStream.read()) != -1) time.append((char) c);
      String timeString = time.toString().trim();
      System.out.println("It is " + timeString + " at " + hostname);
    } // end try
    catch (UnknownHostException e) {
      System.err.println(e);
    } catch (IOException e) {
      System.err.println(e);
    }
  } // end main
コード例 #15
0
  /**
   * serviceClient accepts a client connection and reads lines from the socket. Each line is handed
   * to executeCommand for parsing and execution.
   */
  public void serviceClient() throws java.io.IOException {
    System.out.println("Accepting clients now");
    Socket clientConnection = serverSocket.accept();

    // Arrange to read input from the Socket
    InputStream inputStream = clientConnection.getInputStream();
    bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

    // Arrange to write result across Socket back to client
    OutputStream outputStream = clientConnection.getOutputStream();
    PrintStream printStream = new PrintStream(outputStream);

    System.out.println(
        "Client acquired on port #" + serverSocket.getLocalPort() + ", reading from socket");

    try {
      String commandLine;
      while ((commandLine = bufferedReader.readLine()) != null) {
        try {
          Float result = executeCommand(commandLine);
          // Only BALANCE command returns non-null
          if (result != null) {
            printStream.println(result); // Write it back to the client
          }
        } catch (ATMException atmex) {
          System.out.println("ERROR: " + atmex);
        }
      }
    } catch (SocketException sException) {
      // client has stopped sending commands.  Exit gracefully.
      System.out.println("done");
    }
  }
コード例 #16
0
ファイル: ClientSession.java プロジェクト: JosuaKrause/basex
  /**
   * Constructor, specifying the server host:port combination, login data and an output stream.
   *
   * @param host server name
   * @param port server port
   * @param user user name
   * @param pass password
   * @param output client output; if set to {@code null}, results will be returned as strings.
   * @throws IOException I/O exception
   */
  public ClientSession(
      final String host,
      final int port,
      final String user,
      final String pass,
      final OutputStream output)
      throws IOException {

    super(output);
    ehost = host;
    socket = new Socket();
    try {
      // limit timeout to five seconds
      socket.connect(new InetSocketAddress(host, port), 5000);
    } catch (final IllegalArgumentException ex) {
      throw new BaseXException(ex);
    }
    sin = socket.getInputStream();

    // receive timestamp
    final BufferInput bi = new BufferInput(sin);
    final String ts = bi.readString();

    // send user name and hashed password/timestamp
    sout = PrintOutput.get(socket.getOutputStream());
    send(user);
    send(Token.md5(Token.md5(pass) + ts));
    sout.flush();

    // receive success flag
    if (!ok(bi)) throw new LoginException();
  }
コード例 #17
0
  public void firstRun() throws Exception {

    Socket sock = new Socket(host, new Integer(port).intValue());
    OutputStream os = sock.getOutputStream();
    String get = "GET " + contextRoot + "/test.jsp" + " HTTP/1.0\n";
    System.out.println(get);
    os.write(get.getBytes());
    os.write("\n".getBytes());

    InputStream is = sock.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));

    // Get the JSESSIONID from the response
    String line = null;
    while ((line = br.readLine()) != null) {
      System.out.println(line);
      if (line.startsWith("Set-Cookie:") || line.startsWith("Set-cookie:")) {
        break;
      }
    }

    if (line == null) {
      throw new Exception("Missing Set-Cookie response header");
    }

    String jsessionId = getSessionIdFromCookie(line, JSESSIONID);

    // Store the JSESSIONID in a file
    FileOutputStream fos = new FileOutputStream(JSESSIONID);
    OutputStreamWriter osw = new OutputStreamWriter(fos);
    osw.write(jsessionId);
    osw.close();

    stat.addStatus(TEST_NAME, stat.PASS);
  }
コード例 #18
0
  public void secondRun() throws Exception {
    // Read the JSESSIONID from the previous run
    FileInputStream fis = new FileInputStream(JSESSIONID);
    BufferedReader br = new BufferedReader(new InputStreamReader(fis));
    String jsessionId = br.readLine();
    new File(JSESSIONID).delete();

    Socket sock = new Socket(host, new Integer(port).intValue());
    OutputStream os = sock.getOutputStream();
    String get = "GET " + contextRoot + "/ResumeSession" + " HTTP/1.0\n";
    System.out.println(get);
    os.write(get.getBytes());
    String cookie = "Cookie: " + jsessionId + "\n";
    os.write(cookie.getBytes());
    os.write("\n".getBytes());

    InputStream is = sock.getInputStream();
    br = new BufferedReader(new InputStreamReader(is));

    String line = null;
    boolean found = false;
    while ((line = br.readLine()) != null) {
      System.out.println(line);
      if (line.contains(EXPECTED_RESPONSE)) {
        found = true;
        break;
      }
    }

    if (found) {
      stat.addStatus(TEST_NAME, stat.PASS);
    } else {
      throw new Exception("Wrong response. Expected response: " + EXPECTED_RESPONSE + " not found");
    }
  }
コード例 #19
0
ファイル: Server.java プロジェクト: psy-core/probackup
 public void run() {
   try {
     theInputStream = new BufferedReader(new InputStreamReader(client.getInputStream()));
     theOutputStream = new PrintStream(client.getOutputStream());
     while (true) {
       readin = theInputStream.readLine();
       chat.ta.append(readin + "\n");
     }
   } catch (SocketException e) {
     chat.ta.append("连接中断!\n");
     chat.clientBtn.setEnabled(true);
     chat.serverBtn.setEnabled(true);
     chat.tfaddress.setEnabled(true);
     chat.tfport.setEnabled(true);
     try {
       i--;
       skt.close();
       client.close();
     } catch (IOException err) {
       chat.ta.append(err.toString());
     }
   } catch (IOException e) {
     chat.ta.append(e.toString());
   }
 }
コード例 #20
0
ファイル: JokeClient.java プロジェクト: haha1028/csc435
  /** @return lines read from server. */
  private static String[] getResponse(String clientId, String clientCommand, Socket server)
      throws IOException {

    try {
      /** Create filter I/O streams for the socket, Open our connection to server port . */
      InputStreamReader inputStreamReader = new InputStreamReader(server.getInputStream());
      BufferedReader fromServer = new BufferedReader(inputStreamReader);
      PrintStream toServer = new PrintStream(server.getOutputStream());

      // Send machine name or IP address to server:
      toServer.println(clientId + " " + clientCommand);
      toServer.flush();

      /** Read lines of response from the server,and block while synchronously waiting: */
      final int lines = 2;
      String[] response = new String[lines];
      for (int i = 0; i < lines; i++) {
        String textFromServer = fromServer.readLine();
        response[i] = textFromServer;
        if (textFromServer == null) {
          throw new IOException("unable to read from server, end of the stream has been reached");
        } else {
          System.out.println(textFromServer);
        }
      }
      return response;

    } catch (IOException x) {
      throw x;
    }
  }
コード例 #21
0
  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);
    }
  }
コード例 #22
0
 private PDBTEW2Listener(PDBTExecSingleCltWrkInitSrv srv, Socket s) throws IOException {
   _srv = srv;
   _s = s;
   _ois = new ObjectInputStream(_s.getInputStream());
   _oos = new ObjectOutputStream(_s.getOutputStream());
   _oos.flush();
 }
コード例 #23
0
ファイル: Nurse.java プロジェクト: benghan95/clinicassistant
  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;
  }
コード例 #24
0
  public boolean start() {
    try {
      socket = new Socket(server, port);
    } catch (Exception ec) {
      display("Error connectiong to server:" + ec);
      return false;
    }
    String msg = "Connection accepted " + socket.getInetAddress() + ":" + socket.getPort();
    display(msg);
    try {
      sInput = new ObjectInputStream(socket.getInputStream());
      sOutput = new ObjectOutputStream(socket.getOutputStream());
    } catch (IOException eIO) {
      display("Exception creating new Input/output Streams: " + eIO);
      return false;
    }
    new ListenFromServer().start();
    try {
      sOutput.writeObject(username);
    } catch (IOException eIO) {
      display("Exception doing login : " + eIO);
      disconnect();
      return false;
    }

    return true;
  }
コード例 #25
0
 /**
  * ** Reads a line from the specified socket's input stream ** @param socket The socket to read a
  * line from ** @param maxLen The maximum length of of the line to read ** @param sb The string
  * buffer to use ** @throws IOException if an error occurs or the server has stopped
  */
 protected static String socketReadLine(Socket socket, int maxLen, StringBuffer sb)
     throws IOException {
   if (socket != null) {
     int dataLen = 0;
     StringBuffer data = (sb != null) ? sb : new StringBuffer();
     InputStream input = socket.getInputStream();
     while ((maxLen < 0) || (maxLen > dataLen)) {
       int ch = input.read();
       // Print.logInfo("ReadLine char: " + ch);
       if (ch < 0) {
         // this means that the server has stopped
         throw new IOException("End of input");
       } else if (ch == LineTerminatorChar) {
         // include line terminator in String
         data.append((char) ch);
         dataLen++;
         break;
       } else {
         // append character
         data.append((char) ch);
         dataLen++;
       }
     }
     return data.toString();
   } else {
     return null;
   }
 }
コード例 #26
0
ファイル: SphinxClient.java プロジェクト: nzinfo/csft5
  /** Internal method. Connect to searchd and exchange versions. */
  private Socket _Connect() {
    if (_socket != null) return _socket;

    _connerror = false;
    Socket sock = null;
    try {
      sock = new Socket();
      sock.setSoTimeout(_timeout);
      InetSocketAddress addr = new InetSocketAddress(_host, _port);
      sock.connect(addr, _timeout);

      DataInputStream sIn = new DataInputStream(sock.getInputStream());
      int version = sIn.readInt();
      if (version < 1) {
        sock.close();
        _error = "expected searchd protocol version 1+, got version " + version;
        return null;
      }

      DataOutputStream sOut = new DataOutputStream(sock.getOutputStream());
      sOut.writeInt(VER_MAJOR_PROTO);

    } catch (IOException e) {
      _error = "connection to " + _host + ":" + _port + " failed: " + e;
      _connerror = true;

      try {
        if (sock != null) sock.close();
      } catch (IOException e1) {
      }
      return null;
    }

    return sock;
  }
コード例 #27
0
ファイル: Server.java プロジェクト: blueskyll/Workspace
  /** Create the serversocket and use its stream to receive serialized objects */
  public static void main(String args[]) {

    ServerSocket ser = null;
    Socket soc = null;
    String str = null;
    Date d = null;

    try {
      ser = new ServerSocket(8020);
      /*
       * This will wait for a connection to be made to this socket.
       */
      soc = ser.accept();
      InputStream o = soc.getInputStream();
      ObjectInput s = new ObjectInputStream(o);
      str = (String) s.readObject();
      d = (Date) s.readObject();
      s.close();

      // print out what we just received
      System.out.println(str);
      System.out.println(d);
    } catch (Exception e) {
      System.out.println(e.getMessage());
      System.out.println("Error during serialization");
      System.exit(1);
    }
  }
コード例 #28
0
  @Override
  public void run() {
    // System.out.println ("New Communication Thread Started");

    try {
      BufferedReader in;
      // OUTPUT STREAM
      try (PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) {
        in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        String inputLine;
        // READ NUMBER OF FORTUNE COOKIES CLIENT WANTS
        while ((inputLine = in.readLine()) != null) {
          // System.out.println("Hello");
          if (inputLine.equals("Bye.")) break;
          int number = Integer.parseInt(inputLine);
          System.out.println("Server: " + inputLine);
          // SENDS RANDOMLY GENERATED COOKIES
          out.println(new FortuneCookies().getCookies(number));
        }
      }
      // CLIENT CLOSE
      in.close();
      clientSocket.close();
    } catch (IOException e) {
      System.err.println("Problem with Communication Server");
      System.exit(1);
    }
  }
コード例 #29
0
  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);
    }
  }
コード例 #30
0
  public Server() {
    try {
      ServerSocket ss = new ServerSocket(SERVER_PORT);

      Socket s = ss.accept();

      InputStream is = s.getInputStream();
      OutputStream out = s.getOutputStream();
      InputStreamReader isr = new InputStreamReader(is);
      BufferedReader br = new BufferedReader(isr);

      String sss = br.readLine();
      System.out.println(sss);

      PrintWriter pw = new PrintWriter(out);
      pw.print("hello,我是服务器。");

      pw.close();
      br.close();
      isr.close();
      out.close();
      is.close();
      s.close();
      ss.close();
    } catch (UnknownHostException ue) {
      ue.printStackTrace();
    } catch (IOException oe) {
      oe.printStackTrace();
    }
  }