Wrote a connection to the socket service, send data to the service and receive data after successful connection

Source: Internet
Author: User
Tags socket port number
1, Connecttoserverbytcp This method is connected to the socket service

Directly on the code

public static Socket connecttoserverbytcp (String serverip, int serverport, int timeoutsecond, int Connectcs) {//Establish pass
		Connection Socket othersocket = null;
		Boolean connectok = false;
			try {//creates a stream socket and connects it to the specified port number on the specified host Othersocket = new Socket ();
			System.out.println ("ServerIP" + ServerIP + ", serverport" + serverport);
			SocketAddress socketaddress = new Inetsocketaddress (ServerIP, ServerPort); Receive timeout limit of 5-180 seconds, connection timeout limit in 5 seconds Timeoutsecond = (Timeoutsecond < 1 | | timeoutsecond > 180)?
			1:timeoutsecond; for (int i = 0; i < Connectcs; i++) {try {othersocket.connect (socketaddress, 5000);//Connection timeout limit is 5 seconds OtherS
					Ocket.setsotimeout (Timeoutsecond);//Set read operation timeout time 5-180 seconds Connectok = true;
				Break
				} catch (Exception E1) {Log.error (E1);
				}} if (!connectok) {if (othersocket! = null) othersocket.close ();
			Othersocket = null;
		} return othersocket;
			} catch (Exception e) {log.error (e); E.printstacktrace ();

	} return othersocket; }

2. Send and receive data, BUFS is the data to be sent to the server, BufR is the data returned by the server


public static void Socksend (Socket socketS, Buf bufs,buf BufR) throws Posexception {//Send network data Boolean OK = false;
		String SERR = "";
		DataOutputStream out = null;
			try {if (Bufs.get_datalen () < 1) SERR = "Data length [" + Bufs.get_datalen () + "] invalid";
			Send data to server side out = new DataOutputStream (Sockets.getoutputstream ());
			Out.write (Bufs.get_databuf (), 0, Bufs.get_datalen ());
			Thread.Sleep (200);
			Out.flush ();
			OK = true; Closes the client's output stream.
		Equivalent to adding an end tag to the stream-1. This way the Realine method of the input stream of the server reads a-1 and then ends the ReadLine method Sockets.shutdownoutput ();
			} catch (Exception e) {log.error (e);
			OK = false;
			SERR = E.tostring ();
		E.printstacktrace ();
		
		} if (!ok) throw new Posexception ("", "Send Bank data Exception", SERR);
		Receive Message int getlen = 0;
		InputStream inputstream = null;
		DataInputStream bs = null;
			try {InputStream = Sockets.getinputstream ();
			BS = new DataInputStream (InputStream);
			Bufr.set_datalen (0);
			byte[] data = new byte[4096];
			Getlen = bs.read (data); BUfr.set_buflen (Getlen);
			Log.info ("tcpreadlen======" + Getlen);


				if (Getlen > 1) {system.arraycopy (data, 0, Bufr.get_databuf (), 0, Getlen);
				Bufr.set_datalen (Getlen);
			Log.info ("tcpreceivemsg======" + byteutils.getstring (Bufr.get_databuf ()));
				} else {sErr = "failed to receive data: The actual collection length [" + Getlen + "] is invalid";
				Getlen = 0;
			Bufr.set_datalen (0);
			} bs.close ();
			Inputstream.close ();
			Sockets.close ();
		Log.info ("-------Disconnect the Socket");
			} catch (IOException E2) {Log.error (E2);
		E2.printstacktrace ();
		} if (Getlen < 2) {throw new Posexception ("", "Receive data Failed", SERR); }
	}


3, the simulation test received normal data, OK



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.