JAVA-TCP Network Programming

Source: Internet
Author: User

JAVA-TCP Network Programming Server

Logical thinking:

    1. Create a ServerSocket (port), and the server's socket starts
    2. Call Accept () in the loop, this method will plug the program until a user request is found, returning the user's socket
    3. IO operation of user sockets using multithreading

Note : For Scoket/file to be created, closed, you need to put a try catch, detect IOException, so the network IO part of the whole into a try catch.

1. String manipulation

Output: PrintWriter out=new printwriter (Sock.getoutputstream (), true);

READ: BufferedReader in=new BufferedReader (New InputStreamReader (Sock.getinputstream ()));

Or: Scanner input=new Scanner (Sock.getinputstream ());

2. Byte operation (generally used to transfer files, large size, high efficiency, with Bufferedinputstream/bufferedoutputstream)

Output: Bufferedoutputstream out=new Bufferedoutputstream (Sock.getoutputstream ());

Output: Bufferedinputstream out=new Bufferedinputstream (Sock.getinputstream ());

ImportJava.io.*;Importjava.net.*; Public classTcp_server { Public Static voidMain (string[] args) {intport=8888; Try{ServerSocket sock=NewServerSocket (port); System.out.println ("Server startup, Port:" +Sock.getlocalport ());  while(true) {Socket client=sock.accept ();//* * * Note that accept () is a blocking function that returns the client socket***SYSTEM.OUT.PRINTLN ("Monitoring to TCP connection from:" +client.getremotesocketaddress ()); NewWorkthread (client). Start ();//Multithreading            }            }         Catch(IOException e) {System.out.println ("ERROR Found:" +e.getmessage ()); }        //End Try Catch                }}classWorkthreadextendsthread{Socket sock;  PublicWorkthread (Socket sock) { This. sock=sock; }         Public voidrun () {Try{            //It is implemented here with BufferedReaderBufferedReader in=NewBufferedReader (NewInputStreamReader (Sock.getinputstream ())); PrintWriter out=NewPrintWriter (Sock.getoutputstream (),true); String s=NULL;  while((S=in.readline ())! =NULL){//break will return null                if(S.equals ("End"))                     Break; System.out.println ("Received:" +s); Out.println ("Server:" +s); }                        /*Note that readLine () is a blocking function that plugs into a while ((S=readline ())!=null) and waits for the user's data.             * There are two ways to interrupt the cycle. The client disconnects the TCP program, and In.readline () returns NULL. The user exits normally, the client sends an [end tag] to the server, the server according to the tag, interrupts the loop */System.out.println ("A TCP connection was monitored from:" +sock.getremotesocketaddress () + "disconnected. ");            In.close ();            Out.close ();        Sock.close (); }        Catch(IOException e) {System.out.println (E.getmessage ()); }    }        }

Client

Logical thinking:

    1. Create a socket (IP, port) whose parameters are the IP and port of the destination server
    2. You can then use the socket for IO operations.
Importjava.net.*;ImportJava.io.*;ImportJava.util.*; Public classtcp_client { Public Static voidMain (string[] args) {Scanner in=NewScanner (system.in); Try{                        intport=8888; String IP= "127.0.0.1"; Socket sock=NewSocket (IP, port); //output from SocketPrintWriter out=NewPrintWriter (Sock.getoutputstream (),true); //read from socket, implemented here with scannerScanner input=NewScanner (Sock.getinputstream ());  while(true) {System.out.print ("Please enter the message:"); String s=In.nextline (); if(S.equals ("End") {out.println (s);  Break;                } out.println (s); System.out.println ("Send:" +s); S=Input.nextline (); System.out.println ("Received:" +s);            } in.close ();            Input.close ();            Out.close ();        Sock.close (); }        Catch(IOException e) {System.out.println ("ERROR Found:" +e.getmessage ()); }    }}

JAVA-TCP Network Programming

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.