Java-based socket programming

Source: Internet
Author: User

#开头的废话 # To learn Java has been half a month, the original in the textbook in the word, I think the textbook is very thick, to see not know to go to the SE years. Suddenly on the Internet to see a tutorial, the teacher said that learning programming language books do not have to look too closely, to see a general, know what to say on the good, do not remember, and then you kept, hard to make up, do not understand the time to come back to see good, this is the fastest way. In the mind of a pondering, it is true, according to the previous study of C language situation is not so. So the accelerated look, some of the methods introduced in the book, the class has been quickly browsed, brush to the network of this chapter, I think the socket programming should be a try hand, do not just see not to do fake bashi.

This article is original, please refer to the transfer excerpt from http://www.cnblogs.com/liusxg/p/3917624.html

  Socket Programming :

      A: What is a socket: The socket is a BSD UNIX communication mechanism, often referred to as a "socket", whose English intent is "hole" or "socket". As the name implies, the socket, like its English intent, is a porous socket that can provide multiple ports of connection services.

For a more intuitive understanding of the socket, you can use a socket to describe the socket.

If the socket is a multi-hole socket, the socket is to provide a variety of electrical power supply, different electrical work need voltage and current is not the same, but all kinds of electrical appliances have their own one socket, this is called "Port". Electrical use of electricity can be seen as a network resource or a variety of "flow", electricity is transmitted by the wire, so the socket needs to connect the wire, where the wire is the server and the client connection "Connection". The process of initializing the socket is like buying a socket.

On this side of the socket is the "client", the power plant that provides electricity over the wire is the "server". Both the client and the power plant each have an address, the "IP address". There are also a set of transmission and electricity rules, such as the transmission of electricity required by the number of wires to meet demand, electrical power of the technical parameters, the port is a few holes. This is the "agreement". Under normal circumstances we will not deal with the content of the agreement, that is, the agreement is hidden in front of us.

There are some understandings (pictured from source studio ):

      

     two. How it works : for the server, the server initializes the socket, then the port binds (BIND), then the port listens (listen), calls the Accept block, waits for the client connection request. For the client, the client initializes the socket and then requests a connection (connection). The client requests a connection, the server accepts the request and responds to the request for permission (this involves a TCP three handshake connection), then sends the data, and finally closes the connection, which is an interactive process.

As (pictured from source studio):

      

Client clients source code is as follows:

1 ImportJava.io.*;2 Importjava.net.*;3 4  Public classClient {5 6      Public Static voidMain (string[] args)throwsException {7         //TODO Auto-generated method stubs8         9String ReadLine =NULL;TenString intemp =NULL; One         //String outtemp = null; AString turnline = "\ n"; -         FinalString client = "Client:"; -         FinalString Server = "Server:"; the          -         intPort = 4000; -         byteIpaddresstemp[] = {127, 0, 0, 1}; -InetAddress ipAddress =inetaddress.getbyaddress (ipaddresstemp); +          -         //first, the socket is created directly, the port number 1~1023 for the system, and is usually located outside of 1023 +Socket socket =NewSocket (ipAddress, port); A          at         //create three streams, system input stream BufferedReader Systemin,socket input stream bufferedreader socketin,socket output stream printwriter socketout; -BufferedReader systemin =NewBufferedReader (NewInputStreamReader (system.in)); -BufferedReader Socketin =NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); -PrintWriter socketout =NewPrintWriter (Socket.getoutputstream ()); -          -          while(ReadLine! = "Bye"){ in              - System.out.println (client); toReadLine =systemin.readline (); +             //System.out.println (readline); -              the socketout.println (readline); *Socketout.flush ();//refresh so that the server receives, you can also switch to SOCKETOUT.PRINTLN (ReadLine, ture) $             Panax Notoginseng             //outtemp = ReadLine; -Intemp =socketin.readline (); the              +             //System.out.println (client + outtemp); ASYSTEM.OUT.PRINTLN (server + Turnline +intemp); the              +         } -          $ systemin.close (); $ socketin.close (); - socketout.close (); - socket.close (); the          -     }Wuyi  the}

Servers server source code is as follows:

ImportJava.io.*;Importjava.net.*; Public classServer { Public Static voidMain (string[] args)throwsException {//TODO Auto-generated method stubsString ReadLine=NULL; String intemp=NULL; //String outtemp = null;String turnline = "\ n"; FinalString client = "Client:"; FinalString Server = "Server:"; intPort = 4000; //byte ipaddresstemp[] = {127, 0, 0, 1}; //inetaddress ipAddress = inetaddress.getbyaddress (ipaddresstemp); //first create the ServerSocket directlyServerSocket ServerSocket =NewServerSocket (port); Socket Socket=serversocket.accept (); //create three streams, system input stream BufferedReader Systemin,socket input stream bufferedreader socketin,socket output stream printwriter socketout;BufferedReader systemin =NewBufferedReader (NewInputStreamReader (system.in)); BufferedReader Socketin=NewBufferedReader (NewInputStreamReader (Socket.getinputstream ())); PrintWriter socketout=NewPrintWriter (Socket.getoutputstream ());  while(ReadLine! = "Bye") {intemp=Socketin.readline (); SYSTEM.OUT.PRINTLN (Client+ Turnline +intemp);                        SYSTEM.OUT.PRINTLN (server); ReadLine=Systemin.readline ();            Socketout.println (ReadLine);    Socketout.flush (); //quickly refresh so that the client receives, you can also switch to SOCKETOUT.PRINTLN (ReadLine, ture)//outtemp = ReadLine; //System.out.println (server);} systemin.close ();        Socketin.close ();        Socketout.close ();        Socket.close ();            Serversocket.close (); }}

  

The debug results are as follows:

    

  When debugging to start the server, the client can not find the server can not run.

The operation effect is very good, fortunately is finished writing directly can run, the key is the idea of, thus I summed up a law, no matter what to do, the first to consult the information, understand and understand its principles, but also clear thinking, this way to ensure the success rate of the program. Read more about the Java manual to know the constructors of various classes, and return values. Provide a java manual download URL http://www.jb51.net/books/128276.html

In addition, through the socket programming also learned a debugging tips, that is, multi-monitor debugging according to this small triangle is good

Related Article

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.