JAVA Socket Foundation (Simple implementation)

Source: Internet
Author: User

There are several concepts to learn about sockets:

A Socket refers to each endpoint in an Internet connection. How the Internet connection is created, via the IP address plus port number, for interoperability.

A computer (192.168.3.125:80) "" B computer (192.168.3.111:80) then this one of the IP address + port number is a socket (socket. )

HTTP protocol: Two Internet communications need to comply with a unified application layer protocol, usually referred to as the HTTP protocol. The application layer protocol also has FTP protocol, smpt Simple Mail protocol and so on.

Underlying protocol: IP/TCP protocol. In addition to HTTP compliance, the IP/TCP protocol is also required.

URL: Application layer protocol +IP address + port number + resource path such as http://www.baidu.com/index.html; (The HTTP protocol adheres to the port number 80 by default) file transfer defaults to 21 telnet 23

Several common classes that are available in Java that support socket operations:

InetAddress: That means IP addresses, no constructors. You can use the static method Inetaddress.getlocalhost () and other methods to either the InetAddress object of this machine. The ToString method is to print the IP address. See the API documentation for additional methods.

URL: Resource object. Is the URL object mentioned above.

Socket:send method, Getoutputstream () getInputStream (), etc.

Datagramsocket: Packet, UDP transmits the class that holds the data.

IP/TCP Transmission: Orderly, regular, stable and secure. But at a slower pace.

Service side:

 Packagetcp_ip;ImportJava.io.BufferedReader;Importjava.io.IOException;ImportJava.io.InputStream;ImportJava.io.InputStreamReader;ImportJava.net.ServerSocket;ImportJava.net.Socket;/*** TCP/IP Transport server side *@authorAdministrator **/ Public classServer { Public Static voidMain (string[] args)throwsIOException {//creating a server-side socketServerSocket ServerSocket =NewServerSocket (9999); //set the listening status after creating the ServerSocket for the specified port! Will blockSYSTEM.OUT.PRINTLN ("Socket server started successfully! Listening on port 9999 ... "); Socket Socket=serversocket.accept (); //a socket is returned when the request is successfully receivedInputStream is =Socket.getinputstream (); InputStreamReader ISR=NewInputStreamReader (IS); BufferedReader Reader=NewBufferedReader (ISR); String Data=Reader.readline ();  while(data!=NULL&&!data.equals ("") {System.out.println (data); Data=Reader.readline ();        } reader.close ();        Isr.close ();        Is.close ();            Socket.close (); }}

Client:

 Packagetcp_ip;Importjava.io.IOException;ImportJava.io.OutputStream;ImportJava.io.OutputStreamWriter;ImportJava.net.Socket; Public classClient { Public Static voidMain (string[] args)throwsException {//Create client clients specify destination IP and port (that is, target socket)Socket socket =NewSocket ("localhost", 9999); //or the output stream of this socketOutputStream OutputStream =Socket.getoutputstream (); OutputStreamWriter writer=NewOutputStreamWriter (OutputStream); Writer.write ("I am the client, I send you the content is" + "Hello Ah! Service Side! ");        Writer.close ();        Outputstream.close ();    Socket.close (); }}

Multi-threaded version:

Service side:

 Packagetcp_ip;Importjava.io.IOException;ImportJava.net.ServerSocket;ImportJava.net.Socket; Public classServerthread { Public Static voidMain (string[] args)throwsIOException {//creating a server-side socketServerSocket ServerSocket =NewServerSocket (9999); //set the listening status after creating the ServerSocket for the specified port! Will blockSYSTEM.OUT.PRINTLN ("Socket server started successfully! Listening on port 9999 ... ");  while(true) {Socket Socket=serversocket.accept (); Newrunthread (socket). Start (); }    }}

Client:

 Packagetcp_ip;Importjava.io.IOException;ImportJava.io.OutputStream;ImportJava.io.OutputStreamWriter;ImportJava.net.Socket; Public classClient { Public Static voidMain (string[] args)throwsException {//Create client clients specify destination IP and port (that is, target socket)Socket socket =NewSocket ("localhost", 9999); //or the output stream of this socketOutputStream OutputStream =Socket.getoutputstream (); OutputStreamWriter writer=NewOutputStreamWriter (OutputStream); Writer.write ("I am the client, I send you the content is" + "Hello Ah! Service Side! Send you again ~ ~ ");        Writer.close ();        Outputstream.close ();    Socket.close (); }}

UDP Transport: unordered, irregular, unsafe, fast.

Service side:

 PackageUDP;Importjava.io.IOException;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;Importjava.net.InetAddress;Importjava.net.SocketException;Importjava.net.UnknownHostException;/*** UDP Client *@authorCzt **/ Public classClient { Public Static voidMain (string[] args) {Try{String Data=NewString ("Hello!" ----Message from the client! ". GetBytes ()," Utf-8 "); Datagrampacket Datagrampacket=NewDatagrampacket (Data.getbytes (), Data.length (), Inetaddress.getlocalhost (), 7788); Datagramsocket Socket=NewDatagramsocket ();        Socket.send (Datagrampacket); } Catch(unknownhostexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(SocketException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }            }}

Client:

 PackageUDP;Importjava.io.IOException;ImportJava.net.DatagramPacket;ImportJava.net.DatagramSocket;Importjava.net.InetAddress;Importjava.net.SocketException;Importjava.net.UnknownHostException;/*** UDP Client *@authorCzt **/ Public classClient { Public Static voidMain (string[] args) {Try{String Data=NewString ("Hello!" ----Message from the client! ". GetBytes ()," Utf-8 "); Datagrampacket Datagrampacket=NewDatagrampacket (Data.getbytes (), Data.length (), Inetaddress.getlocalhost (), 7788); Datagramsocket Socket=NewDatagramsocket ();        Socket.send (Datagrampacket); } Catch(unknownhostexception e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(SocketException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }            }}

JAVA Socket Foundation (Simple implementation)

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.