Tag (network)'s result:

java netwrok program—tcp

I use socket in this program. TCPServer.java: import java.io.*; import java.net.*; import java.lang.*; import java.util.*; class TCPServer { public static void main(String argv[]) throws Exception { String clientSentence; String capitalizedSentence; ServerSocket welcomeSocket = new ServerSocket(2345); while(true) { System.out.println(” Server is waitting………\n”); Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); clientSentence = inFromClient.readLine(); Date transfer_date = new Date(); System.out.println(“Received: ” + clientSentence + “—” + transfer_date.toString()); //receive data from client capitalizedSentence = clientSentence.toUpperCase() + ‘\n’; outToClient.writeBytes(capitalizedSentence); //send data to client } } } TCPClient.java: 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)); //get input from keyboard Socket clientSocket = new Socket(“localhost”, 2345); DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); sentence = inFromUser.readLine(); outToServer.writeBytes(sentence + ‘\n’); //send data to server modifiedSentence = inFromServer.readLine(); System.out.println(“FROM SERVER: ” + modifiedSentence); //get data from server clientSocket.close(); } }

Use java to get ip and host name

java.net.* is very useful,this program I use InetAddress to get local ip,host name,baidu ip and baidu’s host name. import java.net.*; public class Localip { public static void main(String[] args) { try { InetAddress address = InetAddress.getLocalHost(); InetAddress baidu = InetAddress.getByName(“www.baidu.com”); System.out.println (address); System.out.println (baidu); System.out.println (“Host Name:” + address.getHostName()); System.out.println (“IP Address:” + address.getHostAddress()); System.out.println (“baidu host name:” + baidu.getHostName()); } catch (UnknownHostException e) { System.out.println(“Could not find local address!”); } } }