Question

Here is an sample TCP/IP Server and Client programms

TCPServer

import java.io.*;
import java.net.*;

    class TCPServer
    {
       public static void main(String argv[]) throws Exception
          {
             String clientSentence;
             String capitalizedSentence;
             ServerSocket welcomeSocket = new ServerSocket(6789);

             while(true)
             {
                Socket connectionSocket = welcomeSocket.accept();
                BufferedReader inFromClient =
                   new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
                DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
                clientSentence = inFromClient.readLine();
                System.out.println("Received: " + clientSentence);
                capitalizedSentence = clientSentence.toUpperCase() + '\n';
                outToClient.writeBytes(capitalizedSentence);
             }
          }
    } 

TCPClient

import java.io.*;
import java.net.*;

class TCPClient
{
 public static void main(String argv[]) throws Exception
 {
  String sentence;
  String modifiedSentence;
  BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
  Socket clientSocket = new Socket("localhost", 6789);
  DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
  BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
  sentence = inFromUser.readLine();
  outToServer.writeBytes(sentence + '\n');
  modifiedSentence = inFromServer.readLine();
  System.out.println("FROM SERVER: " + modifiedSentence);
  clientSocket.close();
 }
}

In that Client i need to send text hi to Server. Onces the server reads that text Hi from Client side it display Client Id with Text is Active now

Était-ce utile?

La solution

Use the socket.getInetAddress() to get an InetAddress object including the IP address then call the InetAddress.getHostAddress() to get it as a string.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top