Java Socket Programming (ii) socket base __ Algorithm

Source: Internet
Author: User

Second, socket base

1. Access to Addresses
	public static void Main (string[] args) {

		try {
			enumeration<networkinterface> interfaces = Networkinterface.getnetworkinterfaces ();
			while (Interfaces.hasmoreelements ()) {
				NetworkInterface iface = Interfaces.nextelement ();
				System.out.println ("Interface:" + iface.getname ());
				
				enumeration<inetaddress> addrlist = iface.getinetaddresses ();
				if (!addrlist.hasmoreelements ())
					System.out.println ("No address");
				
				while (Addrlist.hasmoreelements ()) {
					inetaddress address = addrlist.nextelement ();
					SYSTEM.OUT.PRINTLN ("Address:" + address.gethostaddress ());}}}
			
		catch (SocketException e) {
			e.printstacktrace ();
		}
		
	}

2.TCP Instance Program
Note that while only a write () method is used to send a string on the client side, the server side may accept the information from multiple blocks. Even if the feedback string is stored in a block when the server returns, it may be split into multiple parts by the TCP protocol.
Tcpechoclienttest.java
	public static void Main (string[] args) throws IOException {

		String server = args[0];
		byte[] data = Args[1].getbytes ();
		int port = 7;
		
		Socket socket = new socket (server, port);
		System.out.println ("Connected to Server ...");
		
		InputStream in = Socket.getinputstream ();
		OutputStream out = Socket.getoutputstream ();
		
		Out.write (data);
		
		int TOTALBYTESRCVD = 0;
		int BYTESRCVD;
		while (Totalbytesrcvd < data.length) {
			if (BYTESRCVD = In.read (data, TOTALBYTESRCVD, 
					data.length- TOTALBYTESRCVD) = = = 1)
				throw new SocketException ("Connection closed");
			TOTALBYTESRCVD + + bytesrcvd;
		}
		
		System.out.println ("Received:" + new String (data));
		
		Socket.close ();
	}

Tcpechoservertest.java
	private static final int bufsize =;
	
	public static void Main (string[] args) throws IOException {

		ServerSocket serversocket = new ServerSocket (7);
		
		int recvmsgsize;
		byte[] ReceiveBuf = new Byte[bufsize];
		while (true) {
			socket socket = serversocket.accept ();
			SYSTEM.OUT.PRINTLN ("Handling Client" +
					"from remote" + socket.getremotesocketaddress () + 
					"in local" + socket. Getlocalsocketaddress ());
			
			InputStream in = Socket.getinputstream ();
			OutputStream out = Socket.getoutputstream ();
			
			while ((Recvmsgsize = In.read (receivebuf))!=-1) {
				out.write (receivebuf, 0, recvmsgsize);
			}
			Socket.close ();
		}
		
	
Note When the new socket specifies the port number that the remote server listens on without specifying a local port, the default address and the available port number are used. The client port on my machine is 4593, connecting to Port 7 on the server.

3.UDP Instance Program
Why the UDP protocol is used. If the application swaps only a small amount of data, the TCP connection will have at least two times the amount of information to be transferred (twice times the round-trip time).
Udpechoclienttest.java
	public static void Main (string[] args) throws IOException {inetaddress serveraddress = Inetaddress.getbyname (args[0))
		;
		
		byte[] Bytestosend = Args[1].getbytes ();
		Datagramsocket socket = new Datagramsocket ();
		
		Socket.setsotimeout (3000);
		
		Datagrampacket sendpacket = new Datagrampacket (Bytestosend, Bytestosend.length, serveraddress, 7);
		
		Datagrampacket receivepacket = new Datagrampacket (new Byte[bytestosend.length), bytestosend.length);
		Packets May is lost, so we have to keep trying int tries = 0;
		Boolean receivedresponse = false;
			do {socket.send (sendpacket);
				try {socket.receive (receivepacket);
				if (!receivepacket.getaddress (). Equals (serveraddress)) throw new IOException ("Receive from unknown Source");
			Receivedresponse = true;
				catch (IOException e) {tries++;
			System.out.println ("Timeout, try Again");
		
		} while (!receivedresponse && tries < 5); if (receivedresponse) System.out.println ("Received:" + New String (Receivepacket.getdata ());
		
		else System.out.println ("No response");
	Socket.close (); }

Udpechoservertest.java
	private static final int echomax = 255; 
	
	public static void Main (string[] args) throws IOException {

		datagramsocket socket = new Datagramsocket (7);
		Datagrampacket packet = new Datagrampacket (new Byte[echomax), Echomax);
		
		while (true) {
			socket.receive (packet);
			SYSTEM.OUT.PRINTLN ("Handling client at" + packet.getaddress ());
			
			Socket.send (packet);
			Packet.setlength (Echomax);
		}
		
	
This example compares the previous TCP instances with the following differences:
A.datagramsocket does not need to specify a destination address when it is created, because UDP does not need to establish a connection, and each data message can be sent or received at different destination addresses.
B. If you block the wait on read () Like TCP, it will probably block there forever because the UDP protocol simply expands the IP protocol and the UDP message may be lost. So be sure to set the timeout time for blocking waiting.
The C.UDP protocol retains the boundary information for the message, and the receive () call receives at most one time only the data sent by the Send () method call.
D. A UDP message datagrampacket the maximum data that can be transmitted is 65507 bytes, the excess bytes are automatically discarded, and there is no hint to the receiving program. So the cache array can be set to 65000 bytes or so is safe.
E. If you repeatedly invoke the receive () method with the same Datagrampacket instance, you must explicitly reset the internal length of the message to the actual length of the buffer before each call.
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.