JAVA socket Communication

Source: Internet
Author: User

Development principle: Server, using ServerSocket to listen to the specified port, the port can be specified at Will (because the port below 1024 is usually a reserved port, it cannot be used in some operating systems at will, therefore, we recommend that you use a port greater than 1024). Wait for the client connection request. After the client connects, the session is generated. After the session is completed, the connection is closed. The client uses a Socket to send a connection request to a port of a server on the network. Once the connection is successful, the session is opened. After the session is complete, the Socket is closed. The client does not need to specify the opened port. Generally, a temporary and dynamic port of over 1024 is allocated. Package com. umesage. stop; import java.net. *; import java. io. *; public class Server {private ServerSocket ss; private Socket socket; private BufferedReader in; private PrintWriter out; public Server () {try {ss = new ServerSocket (10000 ); while (true) {socket = ss. accept (); in = new BufferedReader (new InputStreamReader (socket. getInputStream (); out = new PrintWriter (socket. getOutputStream (), true); String Line = in. readLine (); System. out. println ("you input is:" + line); out. println ("you input is:" + line); out. close (); in. close (); socket. close (); ss. close () ;}} catch (IOException e) {}} public static void main (String [] args) {new Server () ;}} package com. umesage. stop; import java. io. *; import java.net. *; public class Client {Socket socket; BufferedReader in; PrintWriter out; public Client () {try {socket = New Socket ("maid", 10000); // in = new BufferedReader (new InputStreamReader (socket //. getInputStream (); out = new PrintWriter (socket. getOutputStream (), true); out. println ("Please Stop! "); Out. close (); // in. close (); socket. close () ;}catch (IOException e) {}} public static void main (String [] args) {new Client ();}}

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.