SHOW:
|
|
- or go back to the newest paste.
| 1 | package org.kodejava.example.net; | |
| 2 | ||
| 3 | import java.io.IOException; | |
| 4 | import java.io.ObjectInputStream; | |
| 5 | import java.io.ObjectOutputStream; | |
| 6 | import java.lang.ClassNotFoundException; | |
| 7 | import java.lang.Runnable; | |
| 8 | import java.lang.Thread; | |
| 9 | import java.net.ServerSocket; | |
| 10 | import java.net.Socket; | |
| 11 | ||
| 12 | public class ServerSocketExample {
| |
| 13 | private ServerSocket server; | |
| 14 | private int port = 7777; | |
| 15 | ||
| 16 | public ServerSocketExample() {
| |
| 17 | try {
| |
| 18 | server = new ServerSocket(port); | |
| 19 | } catch (IOException e) {
| |
| 20 | e.printStackTrace(); | |
| 21 | } | |
| 22 | } | |
| 23 | ||
| 24 | public static void main(String[] args) {
| |
| 25 | // ServerSocketExample example = new ServerSocketExample(); | |
| 26 | // example.handleConnection(); | |
| 27 | } | |
| 28 | ||
| 29 | public void handleConnection() {
| |
| 30 | System.out.println("Waiting for client message...");
| |
| 31 | ||
| 32 | // | |
| 33 | // The server do a loop here to accept all connection initiated by the | |
| 34 | // client application. | |
| 35 | // | |
| 36 | while (true) {
| |
| 37 | try {
| |
| 38 | Socket socket = server.accept(); | |
| 39 | new ConnectionHandler(socket); | |
| 40 | } catch (IOException e) {
| |
| 41 | e.printStackTrace(); | |
| 42 | } | |
| 43 | } | |
| 44 | } | |
| 45 | } | |
| 46 | ||
| 47 | class ConnectionHandler implements Runnable {
| |
| 48 | private Socket socket; | |
| 49 | ||
| 50 | public ConnectionHandler(Socket socket) {
| |
| 51 | this.socket = socket; | |
| 52 | ||
| 53 | Thread t = new Thread(this); | |
| 54 | t.start(); | |
| 55 | } | |
| 56 | ||
| 57 | public void run() {
| |
| 58 | try | |
| 59 | {
| |
| 60 | // | |
| 61 | // Read a message sent by client application | |
| 62 | // | |
| 63 | ObjectInputStream ois = new ObjectInputStream(socket.getInputStream()); | |
| 64 | String message = (String) ois.readObject(); | |
| 65 | System.out.println("Message Received: " + message);
| |
| 66 | ||
| 67 | // | |
| 68 | // Send a response information to the client application | |
| 69 | // | |
| 70 | ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream()); | |
| 71 | oos.writeObject("Hi...");
| |
| 72 | ||
| 73 | ois.close(); | |
| 74 | oos.close(); | |
| 75 | socket.close(); | |
| 76 | ||
| 77 | System.out.println("Waiting for client message...");
| |
| 78 | } catch (IOException e) {
| |
| 79 | e.printStackTrace(); | |
| 80 | } catch (ClassNotFoundException e) {
| |
| 81 | e.printStackTrace(); | |
| 82 | } | |
| 83 | } | |
| 84 | } |