TCP protocol for network programming in Java

Source: Internet
Author: User

I. Basic concepts of TCP is a connection-oriented protocol specially designed to provide reliable and end-to-end byte stream communication on unreliable intel, TCP connections are byte streams rather than Packet streams. Each of UDP and TCP has 65536 port numbers, which do not affect each other. 2. The following code for a Single-threaded server can only implement synchronous conversations between the server and the client. After the server completes processing a client request, it will process another client request. The output result of the server is that Client1 is blocked for 20 seconds and Client2 is not executed. Client2 is executed only after Client1 is blocked. This example can be used to learn the basic syntax of TCP. [Java]/*** TCP client 1 *** @ author Xu Yue **/public class Client1 {public static void main (String [] args) throws Exception {Socket socket = new Socket ("127.0.0.1", 8821); OutputStream OS = socket. getOutputStream (); String msg = "I'm Xu Yue 1"; Thread. sleep (20000); OS. write (msg. getBytes (); OS. flush (); OS. close (); socket. close () ;}/ *** TCP client 2 *** @ author Xu Yue **/public class Client2 {public static void Main (String [] args) throws Exception {Socket socket = new Socket ("127.0.0.1", 8821); OutputStream OS = socket. getOutputStream (); String msg = "I'm Xu Yue 2"; OS. write (msg. getBytes (); OS. flush (); OS. close (); socket. close () ;}/ *** single-threaded TCP Server ** @ author Xu Yue **/public class Server {public static void main (String [] args) throws Exception {// create a tcp Server Object with port 8821 // 8821 is the port number of the server, and the client connects from Port A to port 8821. Port A is random. ServerSocket serverSocket = new ServerSocket (8821); while (true) {// if no client sends a request, the thread is blocked here. The method does not continue to execute Socket socket = serverSocket. accept (); System. out. println ("connected"); InputStream instream = socket. getInputStream (); ByteArrayOutputStream bos = new ByteArrayOutputStream (); int len = 0; byte [] buffer = new byte [1024]; while (len = instream. read (buffer ))! =-1) {bos. write (buffer, 0, len);} instream. close (); bos. flush (); bos. close (); String msg = bos. toString (); System. out. println ("Client IP:" + socket. getInetAddress (). getHostAddress (); System. out. println ("client port:" + socket. getPort (); System. out. println ("client information:" + msg );}}} /*** TCP client 1 *** @ author Xu Yue **/public class Client1 {public static void main (String [] args) throws Exception {Socket socket = New Socket ("127.0.0.1", 8821); OutputStream OS = socket. getOutputStream (); String msg = "I'm Xu Yue 1"; Thread. sleep (20000); OS. write (msg. getBytes (); OS. flush (); OS. close (); socket. close () ;}/ *** TCP client 2 *** @ author Xu Yue **/public class Client2 {public static void main (String [] args) throws Exception {Socket socket = new Socket ("127.0.0.1", 8821); OutputStream OS = socket. getOutputStream (); String msg = "I'm Xu Yue 2"; OS. write (msg. getBytes (); OS. flush (); OS. close (); socket. close () ;}/ *** single-threaded TCP Server ** @ author Xu Yue **/public class Server {public static void main (String [] args) throws Exception {// create a tcp Server Object with port 8821 // 8821 is the port number of the server, and the client connects from Port A to port 8821, port A is A random ServerSocket serverSocket = new ServerSocket (8821); while (true) {// if no client sends A request, the thread is blocked here, and the method does not continue to execute Socket socket = serverSocket. accept (); System. out. println ("connected"); I NputStream instream = socket. getInputStream (); ByteArrayOutputStream bos = new ByteArrayOutputStream (); int len = 0; byte [] buffer = new byte [1024]; while (len = instream. read (buffer ))! =-1) {bos. write (buffer, 0, len);} instream. close (); bos. flush (); bos. close (); String msg = bos. toString (); System. out. println ("Client IP:" + socket. getInetAddress (). getHostAddress (); System. out. println ("client port:" + socket. getPort (); System. out. println ("client information:" + msg) ;}} execution result connected Client IP: 127.0.0.1 client port: 3775 client information: I am the IP of Xu Yue 1connected client: 127.0.0.1 client port: 3787 client information: I am Xu Yue 2 3. in practical applications, a multi-threaded server runs a permanent program on the server and receives Provides services for requests from multiple clients. Multi-threaded Multi-client mechanism is required. The server listens to the specified port for customer requests. Once the listener arrives, a special service thread is started to respond to the request, the server itself enters the listening status immediately after the thread is started, waiting for the arrival of the next customer. As long as the server is configured with the following code, Client1 and Client2 are executed asynchronously. [Java]/*** multithreading server 0 *** @ author Xu Yue **/public class MultiThreadServer0 {// port number private int port = 8821; // server private ServerSocket serverSocket; public MultiThreadServer0 () throws IOException {// create serverSocket = new ServerSocket (port); System. out. println ("server startup");} public void service () {while (true) {Socket socket = null; try {// when the client is connected, the accept method is triggered to establish a connection socket = serverSocket. acce Pt (); new MultiThreadHandler (socket ). start ();} catch (Exception e) {e. printStackTrace () ;}} public static void main (String [] args) throws IOException {new MultiThreadServer1 (). service () ;}/ *** multithreading processing class */class MultiThreadHandler extends Thread {private Socket socket; public MultiThreadHandler (Socket socket) {this. socket = socket;} private BufferedReader getReader (Socket socket) throws IOException {InputStream socketIn = socket. getInputStream (); return new BufferedReader (new InputStreamReader (socketIn);} public void run () {try {BufferedReader br = getReader (socket); String msg = null; while (msg = br. readLine ())! = Null) {System. out. println ("Client IP:" + socket. getInetAddress (). getHostAddress (); System. out. println ("client port:" + socket. getPort (); System. out. println ("client information:" + msg) ;}} catch (IOException e) {e. printStackTrace ();} finally {try {if (socket! = Null) {socket. close () ;}} catch (IOException e) {e. printStackTrace () ;}}}/*** multithreading Server 1 */public class MultiThreadServer1 {// port number private int port = 8821; // server private ServerSocket serverSocket; // thread pool private ExecutorService executorService; // the size of a single CPU thread pool private final int POOL_SIZE = 10; public MultiThreadServer1 () throws IOException {// create server-side serverSocket = new ServerSocket (port ); // Obtain the number of CPUs of the current system www.2cto.com int cpuNums = Runtime. getRuntime (). availableProcessors (); // flexibly defines the thread pool size based on system resources executorService = Executors. newFixedThreadPool (cpuNums * POOL_SIZE); System. out. println ("server startup");} public void service () {while (true) {Socket socket = null; try {// The client will trigger the accept method to establish a connection socket = serverSocket. accept (); // call the thread pool operation executorService.exe cute (new Handler (socket);} catch (Exception e) {e. printStackTrace () ;}} public static void main (String [] args) throws IOException {new MultiThreadServer1 (). service () ;}/ *** multithreading processing class */class Handler implements Runnable {private Socket socket; public Handler (Socket socket) {this. socket = socket;} private BufferedReader getReader (Socket socket) throws IOException {InputStream socketIn = socket. getInputStream (); return n Ew BufferedReader (new InputStreamReader (socketIn);} public void run () {try {BufferedReader br = getReader (socket); String msg = null; while (msg = br. readLine ())! = Null) {System. out. println ("Client IP:" + socket. getInetAddress (). getHostAddress (); System. out. println ("client port:" + socket. getPort (); System. out. println ("client information:" + msg) ;}} catch (IOException e) {e. printStackTrace ();} finally {try {if (socket! = Null) {socket. close () ;}} catch (IOException e) {e. printStackTrace () ;}}}/*** multithreading server 0 *** @ author Xu Yue **/public class MultiThreadServer0 {// port number private int port = 8821; // server private ServerSocket serverSocket; public MultiThreadServer0 () throws IOException {// create server serverSocket = new ServerSocket (port); System. out. println ("server startup");} public void service () {while (true) {Socket socket = null; tr Y {// when the client is connected, the accept method is triggered to establish a connection socket = serverSocket. accept (); new MultiThreadHandler (socket ). start ();} catch (Exception e) {e. printStackTrace () ;}} public static void main (String [] args) throws IOException {new MultiThreadServer1 (). service () ;}/ *** multithreading processing class */class MultiThreadHandler extends Thread {private Socket socket; public MultiThreadHandler (Socket socket) {this. socket = socket;} private BufferedR Eader getReader (Socket socket) throws IOException {www.2cto. comInputStream socketIn = socket. getInputStream (); return new BufferedReader (new InputStreamReader (socketIn);} public void run () {try {BufferedReader br = getReader (socket); String msg = null; while (msg = br. readLine ())! = Null) {System. out. println ("Client IP:" + socket. getInetAddress (). getHostAddress (); System. out. println ("client port:" + socket. getPort (); System. out. println ("client information:" + msg) ;}} catch (IOException e) {e. printStackTrace ();} finally {try {if (socket! = Null) {socket. close () ;}} catch (IOException e) {e. printStackTrace () ;}}}/*** multithreading Server 1 */public class MultiThreadServer1 {// port number private int port = 8821; // server private ServerSocket serverSocket; // thread pool private ExecutorService executorService; // the size of a single CPU thread pool private final int POOL_SIZE = 10; public MultiThreadServer1 () throws IOException {// create server-side serverSocket = new ServerSocket (port); // obtain the number of CPUs of the current system int cpuNu MS = Runtime. getRuntime (). availableProcessors (); // flexibly defines the thread pool size based on system resources executorService = Executors. newFixedThreadPool (cpuNums * POOL_SIZE); System. out. println ("server startup");} public void service () {while (true) {Socket socket = null; try {// The client will trigger the accept method to establish a connection socket = serverSocket. accept (); // call the thread pool operation executorservice.exe cute (new Handler (socket);} catch (Exception e) {e. printStackTrace () ;}} public static vo Id main (String [] args) throws IOException {new MultiThreadServer1 (). service () ;}/ *** multithreading processing class */class Handler implements Runnable {private Socket socket; public Handler (Socket socket) {this. socket = socket;} private BufferedReader getReader (Socket socket) throws IOException {InputStream socketIn = socket. getInputStream (); return new BufferedReader (new InputStreamReader (socketIn);} public void run () {t Ry {BufferedReader br = getReader (socket); String msg = null; while (msg = br. readLine ())! = Null) {System. out. println ("Client IP:" + socket. getInetAddress (). getHostAddress (); System. out. println ("client port:" + socket. getPort (); System. out. println ("client information:" + msg) ;}} catch (IOException e) {e. printStackTrace ();} finally {try {if (socket! = Null) {socket. close () ;}} catch (IOException e) {e. printStackTrace () ;}}} the execution results of the two multi-threaded servers are the same as the IP address of the server to start the client: 127.0.0.1 client port: 3931 client information: I am the IP address of the client Xu Yue 2: 127.0.0.1 client port: 3928 client information: I am Xu Yue 1

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.