Socket basics in java

Source: Internet
Author: User

Basic concepts of Socket
1. socket, also known as socket.
2. Definition in Sun Java: it is the end of a two-way communication connection between two programs running on the network. It provides a connection channel between the client and the server. The socket is bound to a specific port so that the TCP layer knows the application to which data is provided.
3. Literally, socket means "socket, hole". You can also interpret it as a telephone call. You can hear the other party's voice from the receiver, at the same time, the voice is sent to the other party through the microphone.

Socket programming principle
From the establishment of the connection to the end of the connection, each Socket Application generally includes the following basic steps:
1. The server socket is bound to a specific port, and the server listens to the socket waiting for connection requests;
2. The client submits a connection request to the server and a specific port;
3. The server accepts the connection, generates a new socket, and binds it to another port. The socket is used to process and interact with the client. The server continues to listen to the original socket to accept connection requests from other clients;
  
4. After the connection is successful, the client also generates a socket and communicates with the server through it (note: the client socket is not bound to a specific port );
5. Next, the server and client will communicate by reading and writing their respective sockets.

Socket class in Java
Java provides two classes (in the java.net package)-socket and serversocket to implement the client and server socket respectively. However, the actual work of the socket is done by the instance of the abstract class socketimpl, which is actually an application of the abstract factory mode in the design mode.
  
Common constructors and main methods of serversocket classes:
  
Serversocket (INT port) generates a server socket on the specified port number.
Socket accept ()
Listen to socket and accept connection
Common constructors and main methods of socket classes:
  
Socket (string host, int port) generates a socket and connects to the specified host and Port
Inputstream getinputstream () returns the socket input stream
Outputstream getouputstream () returns the socket output stream

One customer server instance
In this example, we simulate an echo service that listens on port 3333. The client accepts user keyboard input and sends a connection request to the server. The server accepts the client connection and establishes a session after the connection is successful. The client then sends the user input information to the server, the server receives this information and simply returns it to the client. The source code is as follows:
  
(Server)
  
/**
* <P> title: echoserver. Java </P>
* <P> Description: echoserver create a echo-like server at Port 3333 </P>
* @ Author Mac
* @ Version 2002/9/2
*/
  
Import java.net .*;
Import java. Io .*;
  
Public class echoserver
{
Public static void main (string [] ARGs) throws ioexception
{
Serversocket echoserver = NULL;
Try
{
EchoServer = new ServerSocket (3333); // creat a server socket at port
3333 (question 1)
}
Catch (IOException e)
{
System. err. println ("Couldn't listen on port: 3333 ");
System. exit (-1 );
}
  
Socket echoClient = null;
Try
{
EchoClient = echoServer. accept (); // accept a connection
}
Catch (IOException e)
{
System. err. println ("IO error:" + e. getMessage ());
System. exit (-1 );
}
  
PrintWriter out = new PrintWriter (echoClient. getOutputStream (), true );
// Gets the socket's output stream and opens a PrintWriter on it
// If you remove the argument true, what will happen? (Question 3)
BufferedReader in = new BufferedReader (
New InputStreamReader (echoClient. getInputStream ()));
// Gets the socket's input stream and opens a BufferedReader on it
String strFromClient;
  
While (strFromClient = in. readLine ())! = Null)
{
Out. println ("result is:" + strFromClient );
}
  
In. close ();
Out. close ();
EchoClient. close ();
EchoServer. close ();
}
}
  
(Client)
/**
* <P> Title: EchoClient. java </p>
* <P> Description: EchoClient creates a socket thereby getting a connection
Echo-like server </p>
* @ Author Mac Wang
* @ Version 2002/8/30
*/
  
Import java.net .*;

Public class EchoClient
{
  
Public static void main (String [] args)
{
Try
{
Socket echoClient = new Socket ("yourhostname", 3333 );
// Creat a new socket connected to host and port 3333
PrintWriter out = new PrintWriter (echoClient. getOutputStream (), true );
  
BufferedReader in = new BufferedReader (
New InputStreamReader (echoClient. getInputStream ()));
String fromServer, fromUser;
BufferedReader stdIn = new BufferedReader (
New InputStreamReader (System. in ));
// Gets the system input stream and opens a BufferedReader on it
While (fromUser = stdIn. readLine ())! = Null)
{
If (fromUser. equals ("bye") break;
// When user types "bye" then end
  
System. out. println ("input is:" + fromUser );
Out. println (fromUser );
  
FromServer = in. readLine ();
System. out. println (fromServer );
}
Out. close ();
In. close ();
EchoClient. close ();
}
Catch (UnknownHostException e)
{
System. err. println ("Unknown host: yourhostname ");
System. exit (1 );
}
Catch (IOException e)
{
System. err. println ("I/0 error:" + e. getMessage ());
System. exit (1 );
}
}
}

Think about the following questions:
  
1. Change the port number to 2222 to check the running effect? What about 89? Can it be any number?
  
2. If we do not use our own echo server, but connect to the echo server provided by the system itself (Port Number: 7), what will happen? Does the client Socket need to be changed?
  
3. Remove the parameter True in PrintWriter to check the running effect?
  
4. note how the Socket is read and written in the program?
5. Try to open several more clients to see how they work?

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.