Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.kietna.tcpserver;
- /*
- Translated by Nguyen Anh Kiet
- Source: http://www2.ic.uff.br/~michael/kr1999/2-application/2_06-sockettcp.htm
- Cách đọc: Đọc giải thích ở trên, Code ở dưới.
- */
- /*
- java.io Chứng các classes phục vụ input và output streams như BufferedReader and DataOutputStream
- java.net chức các class hỗ trợ về mạng. Cụ thể là Socket classes (ServerSocket hoặc clientSocket )
- */
- import java.io.*;
- import java.net.*;
- public class main {
- public static void main(String[] args) throws IOException {
- /*
- Khai báo 2 String
- clientSentence: String nhận được từ người dùng
- capitalizedSentence: String đã được viết hoa để trả về người dùng
- */
- String clientSentence;
- String capitalizedSentence;
- // Tạo 1 Object kiểu ServerSocket mang tên WelcomeSocket, có số hiệu 6789 để lắng nghe kết nối từ Client
- ServerSocket welcomeSocket = new ServerSocket(6789); //Replace 6789 to listening port you want
- /*
- The above line creates a new socket, called connectionSocket, when some client knocks on welcomeSocket.
- TCP then establishes a direct virtual pipe between clientSocket at the client and connectionSocket at the server.
- The client and server can then send bytes to each other over the pipe, and all bytes sent arrive at the other side in order.
- With connectionSocket established, the server can continue to listen for other requests from other clients for the application using welcomeSocket.
- (This version of the program doesn't actually listen for more connection requests. But it can be modified with threads to do so.)
- The program then creates several stream objects, analogous to the stream objects created in clientSocket.
- */
- while(true){
- /*
- Tạo một Socket mới mang tên connectionSocket.
- Khi Client kết nối với welcomeSocket.
- TCP tạo ra một đường dẫn ảo giữa clientSocket ở Client và connectionSocket ở Server
- Client và Server sẽ gửi thông tin qua đường dẫn này
- Việc thiết lập connectionSocket cho phép server có thể tiếp tục lắng nghe các request từ các client khác thông qua welcomeSocket
- */
- Socket connectionSocket = welcomeSocket.accept();
- /*
- Tạo 2 đối tượng Stream đính kèm với connectionSocket
- inFromClient lấy dữ liệu từ Client
- outToClient gửi dữ liệu về Client
- */
- BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
- DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
- // Đọc chuỗi clientSentence từ client gửi lên
- clientSentence = inFromClient.readLine();
- // Tạo ra chuỗi in hoa capitalizedSentence bằng thông tin từ chuỗi clientSentence hàm toUpperCase()
- capitalizedSentence = clientSentence.toUpperCase() + '\n';
- // Gửi lại chuỗi về Client qua stream outToClient
- outToClient.writeBytes(capitalizedSentence);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement