bangnaga

Simple Java Socket Programming

Jun 1st, 2012
107
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.io.OutputStream;
  5. import java.io.PrintWriter;
  6. import java.net.ServerSocket;
  7. import java.net.Socket;
  8.  
  9. public class TestServerSocket {
  10.  
  11.     public static void main(String args[]) throws IOException {
  12.         final int portNumber = 81;
  13.         System.out.println("Creating server socket on port " + portNumber);
  14.         ServerSocket serverSocket = new ServerSocket(portNumber);
  15.         while (true) {
  16.             Socket socket = serverSocket.accept();
  17.             OutputStream os = socket.getOutputStream();
  18.             PrintWriter pw = new PrintWriter(os, true);
  19.             pw.println("What's you name?");
  20.  
  21.             BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
  22.             String str = br.readLine();
  23.  
  24.             pw.println("Hello, " + str);
  25.             pw.close();
  26.             socket.close();
  27.  
  28.             System.out.println("Just said hello to:" + str);
  29.         }
  30.     }
  31. }
RAW Paste Data