Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * To change this license header, choose License Headers in Project Properties.
- * To change this template file, choose Tools | Templates
- * and open the template in the editor.
- */
- import java.io.*;
- import java.net.*;
- import java.util.*;
- public class TCPServer2 {
- //input command line could be java TCPServer2 [port [IP]]
- public static void main(String argv[]) throws Exception
- {
- final int NUM_BYTES = 80;
- int portNum = 11234; //default server's port number, remember to change yours
- String servIP="localhost"; //default server's IP
- if (argv.length > 0)
- try {
- portNum = Integer.parseInt(argv[0]);
- } catch (NumberFormatException e) {
- System.err.println("First argument must be an integer");
- System.exit(1);
- }
- if (argv.length > 1)
- servIP = argv[1]; //get the IP
- ServerSocket welcomeSocket = null;
- //BufferedInputStream inFromClient = null;
- String sentence;
- byte[] buf = new byte[NUM_BYTES];
- try {
- welcomeSocket = new ServerSocket(portNum); //bind to the server's port number
- System.out.println ("Connection Socket Created");
- while (true)
- {
- try (Socket connectionSocket = welcomeSocket.accept(); BufferedInputStream inFromClient = new BufferedInputStream(connectionSocket.getInputStream()); PrintWriter outToClient = new PrintWriter(connectionSocket.getOutputStream(),true)) {
- // wait for client's message
- System.out.print("Wait for client's message...");
- int nRead = inFromClient.read(buf,0,NUM_BYTES);
- if (nRead<=0)
- {
- inFromClient.close(); //since client has closed socket.
- connectionSocket.close();
- continue; // serve next one
- }
- System.out.println(nRead);
- System.out.write(buf,0,nRead);
- System.out.println("");
- //Set up stream for keyboard entry...
- Scanner inFromUser = new Scanner(System.in);
- System.out.print("Enter message: ");
- sentence = inFromUser.nextLine();
- outToClient.println(sentence);
- outToClient.flush();
- }
- }
- }
- catch(IOException ioEx)
- {
- System.out.println("Exception ");
- }
- finally {
- welcomeSocket.close();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement