本文介绍如何用Java实现Socket编程。首先介绍Java针对Socket编程提供的类,以及它们之间的关系。然后分别针对TCP和UDP两种传输层协议实现Socket编程。
Introduction to socket programming interface in 1 Java
Java encapsulates several important classes for socket programming. 1.1 Socket Class
Socket class implements a client socket, as the terminal of two machines communication, the default Transport layer protocol is TCP, is a reliable transmission protocol. The socket class also provides the Connect, Getoutputstream, getInputStream, and close methods in addition to the constructor function to return a socket. The Connect method is used to request a socket connection, Getoutputstream is used to obtain the output stream of the write socket, getInputStream is used to obtain the input stream for the read socket, and the Close method is used to turn off a stream. 1.2 Datagramsocket class
The Datagramsocket class implements a socket for sending and receiving datagrams, and the Transport Layer protocol uses UDP to guarantee the reliable transmission of datagrams. Datagramsocket mainly has send, receive and close three methods. Send is used to send a datagram, Java provides a Datagrampacket object to express a datagram. Receives is used to receive a datagram, which is blocked until the datagram or timeout is received until the method is invoked. Close is to turn off a socket. 1.3 ServerSocket class
The ServerSocket class implements a server socket, a server socket waits for a client network request, and then executes the action based on those requests and returns a result to the requester. The ServerSocket provides bind, accept, and close three methods. The Bind method binds an IP address and port to the ServerSocket and starts listening on the port. The Accept method accepts the request for ServerSocket and returns a socket object that, after accept method invocation, blocks until a request arrives. The Close method closes a ServerSocket object. 1.4 socketaddress
SocketAddress provides a socket address that does not care about the Transport layer protocol. This is a virtual class that is implemented by subclasses to implement functions and bind transport protocols. It provides an immutable object that is used by the socket to bind, connect, or return a value. 1.5 inetsocketaddress
Inetsocketaddress implements the IP address of the socketaddress, that is, the IP address and port number to express the socket address. If you do not make a specific IP address and port number, then the IP address defaults to the local address, the port number randomly select one. 1.6. Datagrampacket
Datagramsocket is an optional channel for datagram socket communication. The datagram channel is not a complete abstraction of the network datagram socket communication. The control of socket communication is implemented by Datagramsocket object. Datagrampacket needs to be used in conjunction with Datagramsocket to complete a datagram based socket communication.
2. Socket programming based on TCP
It describes the interface provided by Java for Socket programming, and this section describes how to implement a socket communication based on a TCP connection.
The following example is where the server side waits for a message to be received from the client side, and then sends a message to clients.
The
Server-side first instantiates the ServerSocket object, binds it to a native address, and starts listening. Waits for a client request when a client connection request is received, and returns a socket object after it has been blocked. Then use this socket to receive a message and send a message. The code is as follows:
Package Server.socket.java;
Import java.io.IOException;
Import Java.io.PrintWriter;
Import java.net.InetAddress;
Import java.net.InetSocketAddress;
Import Java.net.ServerSocket;
Import Java.net.Socket;
Import java.net.SocketAddress;
public class Sockettcp {static private String TAG = "sockettcp:";
public static void Main (string[] args) {try {serversocket server = new ServerSocket ();
SocketAddress address = new Inetsocketaddress (Inetaddress.getlocalhost (), 10001);
Server.bind (address);
System.out.println ("==waiting for being connected ...");
Socket client = Server.accept ();
System.out.println ("==connected with" + client.getremotesocketaddress ());
PrintWriter socketout = new PrintWriter (Client.getoutputstream ());
SYSTEM.OUT.PRINTLN ("==waiting Message from client ...");
byte buf[] = new byte[1024];if (Client.getinputstream (). Read (BUF) > 0) {System.out.println ("Receive message:" + new String (BUF)
);
} System.out.println ("==sending Message to client ...");
String Sendstr = "This is the message for client.";
Socketout.write (SENDSTR);
Socketout.flush ();
Socketout.close ();
Client.close ();
Server.close ();
catch (IOException e) {System.out.println (TAG + e.getmessage ());
E.printstacktrace (); }
}
}
The client first instantiates a socket object and uses this object to connect to the server side. When the connection succeeds, a message is sent, and then a message is waiting to be received. The code is as follows:
Package Client.socket.java;
Import Java.io.BufferedReader;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.PrintWriter;
Import java.net.InetAddress;
Import java.net.InetSocketAddress;
Import Java.net.Socket;
Import java.net.SocketAddress;
public class Sockettcp {static private String TAG = "sockettcp:";
public static void Main (string[] args) {try {final socket socket = new socket ();
SocketAddress address = new Inetsocketaddress (Inetaddress.getlocalhost (), 10001);
System.out.println ("==connecting to Server ...");
Socket.connect (address);
PrintWriter socketout = new PrintWriter (Socket.getoutputstream ());
BufferedReader socketin = new BufferedReader (New InputStreamReader (Socket.getinputstream ()));
String Sendstr = "This is the message for server." SYSTEM.OUT.PRINTLN ("==sending message to ServEr ... ");
Socketout.write (SENDSTR);
Socketout.flush ();
SYSTEM.OUT.PRINTLN ("==waiting Message from server ...");
String receivestr = Socketin.readline ();
SYSTEM.OUT.PRINTLN ("Receive message:" + receivestr);
Socketout.close ();
Socketin.close ();
Socket.close ();
catch (IOException e) {System.out.println (TAG + e.getmessage ());
E.printstacktrace (); } finally {}}}
Server-side Run results:
==waiting for being connected
... ==connected with/172.26.176.69:53912
==waiting message from client ...
Receive Message:this is the message for server.
Client Run Results:
==connecting to server ...
==sending message to server ...
==waiting message from server ...
Receive Message:this is the message for client.
3 example of socket programming based on UDP
Socket programming based on UDP differs slightly from TCP based socket programming, and socket server and client are implemented with Datagramsocket.
The following example is where the server side waits for a message to be received from the client side, and then sends a message to clients.
The server side first instantiates the Datagramsocket object, binds it to a native address, and starts listening. Waits to receive datagrams from the client in a blocked state. Then get the source address of the datagram from the datagram, and then package a datagram with the source address as the destination address and send it out. The code is as follows:
Package Server.socket.java;
Import java.io.IOException;
Import Java.net.DatagramPacket;
Import Java.net.DatagramSocket;
Import java.net.InetAddress;
Import java.net.InetSocketAddress;
Import java.net.SocketAddress;
Import java.net.SocketException;
Import java.net.UnknownHostException;
public class Socketudp {final private static String TAG = "SOCKETUDP:";
public static void Main (String args[]) {datagramsocket socket = null;
Datagrampacket datapacket = null;
Inetsocketaddress address = null;
try {address = new inetsocketaddress (Inetaddress.getlocalhost (), 7778);
Socket = new Datagramsocket (address);
Socket.bind (address);
byte buf[] = new byte[1024];
Datapacket = new Datagrampacket (buf, buf.length);
System.out.println ("==block for receive messages ...");
Socket.receive (Datapacket);
BUF = Datapacket.getdata (); InetAddress addr = datapacket.getaddress ();
int port = Datapacket.getport ();
SYSTEM.OUT.PRINTLN ("message Content:" + new String (BUF));
System.out.println ("Receive from" + addr + ":" + port);
SocketAddress toaddress = datapacket.getsocketaddress ();
String sendstr = "I ' m Server, this is the message for client.";
BUF = Sendstr.getbytes ();
Datapacket = new Datagrampacket (buf, buf.length);
Datapacket.setsocketaddress (toaddress);
Socket.send (Datapacket);
System.out.println ("==message sended");
catch (Unknownhostexception e) {System.out.println (TAG + e.getmessage ());
E.printstacktrace ();
catch (SocketException e) {System.out.println (TAG + e.getmessage ());
E.printstacktrace ();
catch (IOException e) {System.out.println (TAG + e.getmessage ()); E. Printstacktrace (); }
}
}
The client first instantiates a Datagramsocket object. Package a datagram using the server address and port number as the destination address and send it. Then wait for the datagram to be returned from the server. The code is as follows:
Package Client.socket.java;
Import java.io.IOException;
Import Java.net.DatagramPacket;
Import Java.net.DatagramSocket;
Import java.net.InetAddress;
Import java.net.InetSocketAddress;
Import java.net.SocketException;
Import java.net.UnknownHostException;
public class Socketudp {
final private static String TAG = "SOCKETUDP:";
public static void Main (String args[]) {
try {
Datagramsocket getsocket = new Datagramsocket ();
Datagrampacket datapacket = null;
Inetsocketaddress toaddress = new Inetsocketaddress (Inetaddress.getlocalhost (), 7778);