<< Previous | Table of Categories | Next >> |
After we learnt how the NIO2 works, let's review the traditional socket programming
Traditional TCP Server
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class TraditionalTcpSocketServer { public static void main(String[] argv) throws Exception { String clientSentence; ServerSocket welcomeSocket = new ServerSocket(9001); 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("FROM CLIENT: " + clientSentence); outToClient.writeBytes("World" + System.getProperty("line.separator")); } } }Traditional TCP Client
import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.InputStreamReader; import java.net.Socket; public class TraditionalTcpSocketClient { public static void main(String[] argv) throws Exception { String sentence = "Hello"; String modifiedSentence; Socket clientSocket = new Socket("localhost", 9001); DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); outToServer.writeBytes(sentence + System.getProperty("line.separator")); modifiedSentence = inFromServer.readLine(); System.out.println("FROM SERVER: " + modifiedSentence); clientSocket.close(); } }
No comments:
Post a Comment