Java by API/java.net/ServerSocket

Материал из Java эксперт
Перейти к: навигация, поиск

new ServerSocket(int port)

/*
 * Output:
 *  
 */
import java.io.DataOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class MainClass {
  public static void main(String args[]) {
    try {
      int port = 5555;
      ServerSocket ss = new ServerSocket(port);
      while (true) {
        // Accept incoming requests
        Socket s = ss.accept();
        // Write result to client
        OutputStream os = s.getOutputStream();
        DataOutputStream dos = new DataOutputStream(os);
        dos.writeInt(100);
        s.close();
      }
    } catch (Exception e) {
      System.out.println("Exception: " + e);
    }
  }
}





ServerSocket: accept()

/*
 * Output:
 *  
 */
import java.io.DataOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class MainClass {
  public static void main(String args[]) {
    try {
      int port = 5555;
      ServerSocket ss = new ServerSocket(port);
      while (true) {
        // Accept incoming requests
        Socket s = ss.accept();
        // Write result to client
        OutputStream os = s.getOutputStream();
        DataOutputStream dos = new DataOutputStream(os);
        dos.writeInt(100);
        s.close();
      }
    } catch (Exception e) {
      System.out.println("Exception: " + e);
    }
  }
}





ServerSocket: bind(SocketAddress endpoint)

import java.nio.CharBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
public class MainClass {
  public static void main(String[] args) throws Exception{
    CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();
    ServerSocketChannel server = ServerSocketChannel.open();
    server.socket().bind(new java.net.InetSocketAddress(8000));
    for (;;) { // This server runs forever
      SocketChannel client = server.accept();
      String response = new java.util.Date().toString() + "\r\n";
      client.write(encoder.encode(CharBuffer.wrap(response)));
      client.close();
    }
  }
}





ServerSocket: getLocalPort()

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class MainClass extends Thread {
  private ServerSocket serverSocket;
  public MainClass(int port) throws IOException {
    serverSocket = new ServerSocket(port);
  }
  public void run() {
    while (true) {
      try {
        System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
        Socket server = serverSocket.accept();
        System.out.println("Just connected to " + server.getRemoteSocketAddress());
        DataInputStream in = new DataInputStream(server.getInputStream());
        System.out.println(in.readUTF());
        DataOutputStream out = new DataOutputStream(server.getOutputStream());
        out
            .writeUTF("Thank you for connecting to " + server.getLocalSocketAddress()
                + "\nGoodbye!");
        server.close();
      } catch (SocketTimeoutException s) {
        System.out.println("Socket timed out!");
        break;
      } catch (IOException e) {
        e.printStackTrace();
        break;
      }
    }
  }
  public static void main(String[] args) {
    int port = Integer.parseInt(args[0]);
    try {
      Thread t = new MainClass(port);
      t.start();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}





ServerSocket: readUTF() and writeUTF(String str)

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class MainClass extends Thread {
  private ServerSocket serverSocket;
  public MainClass() throws IOException {
    serverSocket = new ServerSocket(2000);
  }
  public void run() {
    try {
      Socket client = serverSocket.accept();
      DataInputStream in = new DataInputStream(client.getInputStream());
      BufferedReader console = new BufferedReader(new InputStreamReader(System.in));
      DataOutputStream out = new DataOutputStream(client.getOutputStream());
      while (true) {
        String message = in.readUTF();
        System.out.println(message);
        System.out.print("Enter response: ");
        String response = console.readLine();
        out.writeUTF(response);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  public static void main(String[] args) {
    try {
      Thread t = new MainClass();
      t.start();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}





ServerSocket: setSoTimeout(int timeout)

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class MainClass extends Thread {
  private ServerSocket serverSocket;
  public MainClass() throws IOException {
    serverSocket = new ServerSocket(8008);
    serverSocket.setSoTimeout(10000);
  }
  public void run() {
    while (true) {
      try {
        System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
        Socket client = serverSocket.accept();
        System.out.println("Just connected to " + client.getRemoteSocketAddress());
        client.close();
      } catch (SocketTimeoutException s) {
        System.out.println("Socket timed out!");
        break;
      } catch (IOException e) {
        e.printStackTrace();
        break;
      }
    }
  }
  public static void main(String[] args) {
    try {
      Thread t = new MainClass();
      t.start();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}