How to accept multiple packets through socket

Source: Internet
Author: User
I am using a Java Socket Client.
Protocol
Packet structure (, 51)
The general packet structure is divided into two parts: the packet header and the packet body.
The following is a complete PDU (Protocol Data Unit) Layout:
PDU domain length type description
Header length 4 integer this field indicates the total length of the message package = Header Length + package length, in bytes of the network. The maximum length of a single PDU is 30 kb. If it exceeds the maximum length, subcontracting is required.
Factorycode 1 integer manufacturer code, fixed, fill in 0xa8.
Progid 1 integer process number, fixed, enter 0x0 C.
Whether morepkt 1 integer has subsequent packages, 0x01: Yes, 0x00: No.
Consumer _id 10 string command, ending with null.
Start_num 4 integer start record number, fixed, fill in 0x00000000.
End_num 4 integer termination record number, fixed. Enter 0x00000000.
Request_id 4 integer Request ID, in bytes of the network. Generated by the customer service system. The original value is returned when a third-party system responds, which uniquely identifies a business call.
Answer_id 4 integer response ID, fixed. Enter 0x00000000.
Sequence 4 integer subcontracting number. Set this parameter to 0x00 when sending the customer service package. If the data returned by a third-party system is less than 30 kb, only one package is returned, and set this parameter to 0x01; if the data returned by a third party is greater than 30 kb, enter 0x01, 0x02 ,... 0x **.
Rec_seperator 5 string record separator, fixed, fill in ";", that is, 0x3b00000000.
Field_seperator 5 string field separator, fixed, fill in "~ ", That is, 0x7e00000000.
Reserved1 4 integer reserved, fixed, 0x00000000.
Reserved2 4 integer reserved, fixed, 0x00000000.
Errorcode 2 integer reserved, fixed, 0x0000.
Package datatrans n string request message or response message. The length is not fixed and ends with null. For the specific format and length, see business definition.

1.2 protocol description
1. The package is variable-length, and the total length is specified by the length field.
2. Both the sending and receiving packages use this structure.
3. The process number is generated by the customer service system and cannot be changed by a third-party system. The frontend of a third-party system identifies a client based on the connected IP address and process number to determine which packets are returned to which client.
4. The request ID is generated by the customer service system. When the third-party system sends data back, the corresponding request ID is sent back.
5. whether there is a subsequent package morepkt: if the data returned by a third-party system is less than 30 kb, only one package is returned. Enter 0x00 to indicate that no subsequent package exists (this is the last package ); if the data returned by a third party is greater than 30 kb, subcontracting is performed. If the last package is 0x00, no subsequent package exists. If the other package is 0x01, the subsequent package exists.
6. The record separator and field separator are specified by the customer service system to control the transmitted content. When a third-party system sends back packets, rec_seperator and field_seperator are sent back as they are, and the delivery content is organized according to rec_seperator and field_seperator. For details, see the RANS discussion section.
7. datatrans is the data content actually sent or received. It is actually a variable-length array, and the data content is arranged backward.
8. errorcode is the return code, indicating whether the request has been processed successfully and is not used.
9. The format of the data packet sent by the customer service system is:
Parameter 1 ~ Parameter 2 ~ Parameters 3 ~... Parameter N;
10. Format of the third-party system return data packet datatrans:
Return Value ~ Return description; Record 1;... record N;
Record format: Field 1 ~ Field 2 ~... Field M.
NOTE 1: The number of fields in each record must be equal.
Note 2: The actual transfer of each field is transmitted as a string.
NOTE 3: In the case of multiple packages, a record cannot be truncated and appears in both packages.
1.2 business processing methods
Query all the results at a time and send them back to the customer service system.
If the returned data is less than 30 kb, a packet is returned and cannot be subcontracted. // Therefore, determine whether the rrans part is too long Based on the record.
If the returned data is greater than or equal to 30 kb, multiple packets are returned and must be subcontracted.
In the case of multiple packages, a record cannot be truncated and appears in both packages.
My program is always unable to receive packets from the service end, sometimes it can be fully accepted, sometimes it fails, and there is a great chance of failure. Hope you can help me!
I will send my program to you

Package com. ZTE. usmip. Adapter. henantelwk;

Import java. Io. bufferedoutputstream;
Import java. Io. ioexception;
Import java.net. inetsocketaddress;
Import java. NiO. bytebuffer;
Import java. NiO. channels. socketchannel;
Import java. util. arraylist;
Import java. util. List;

Import com. ZTE. Socket. containerclient;
Import com. ZTE. Utility. autoresetevent;
Import com. ZTE. Utility. confighelper;
Import com. ZTE. Utility. datautil;
Import com. ZTE. Utility. loghelper;
Import com. ZTE. Utility. stringhelper;

Public class socketclient implements runnable
{
// Constructor
Public socketclient (socketcontainer CC ){
This. setcontainerclient (CC );
}
// Container reference
Private socketcontainer containerclient = NULL;
Public socketcontainer getcontainerclient (){
Return this. containerclient;
}
Public void setcontainerclient (socketcontainer CC ){
This. containerclient = cc;
}
// Size of the receiving buffer
Private int buffersize = 30720;
Public int getbuffersize (){
Return this. buffersize;
}
Public void setbuffersize (INT buffersize ){
This. buffersize = buffersize;
}
// Terminal number corresponding to socket
Private string termid = "";
Public String gettermid (){
Return this. termid;
}
Public void settermid (string termid ){
This. termid = termid;
}

Private Boolean connectok = false;
/**
* @ Return the loginok
*/
Public Boolean getconnectok (){
Return this. connectok;
}
/**
* @ Param loginok the loginok to set
*/
Public void setconnectok (Boolean connectok ){
This. connectok = connectok;
}

// Communication socket Channel
Protected socketchannel m_channel = NULL;

/**
* Connect to the server
* @ Param strip Server IP address (DNS domain name supported)
* @ Param nport: server port number
* @ Return
*/
Public Boolean connect (
String strip, int nport ){
If (this. m_channel! = NULL ){
Return false;
}
// Construct an endpoint
Inetsocketaddress address =
New inetsocketaddress (strip, nport );
// Connect to the server
Try {
This. m_channel = socketchannel. Open (Address );
This. setconnectok (true );
} Catch (exception ex ){
Ex. printstacktrace ();
This. m_channel = NULL;
Return false;
}
// Start the receiving thread
This. startrecivethread ();
// Return success
Return true;
}

// Disable socekt
Public void close (){
If (this. m_channel = NULL) return;
Try {
This. m_channel.socket (). shutdowninput ();
} Catch (ioexception e ){
System. Out. println ("unable to close socket input stream ");
E. printstacktrace ();
}
Try {
This. m_channel.socket (). shutdownoutput ();
} Catch (ioexception e ){
System. Out. println ("unable to close socket output stream ");
E. printstacktrace ();
}
Try {
This. m_channel.close ();
} Catch (ioexception e ){
System. Out. println ("cannot close socket ");
E. printstacktrace ();
}
This. m_channel = NULL;
}

// The last received data
Protected byte [] m_receive_data = NULL;
// Subcontract data
Protected byte [] m_temp_data = NULL;
// Subcontract data
Protected byte [] m_temp_data1 = NULL;
// The last data synchronization event
Protected autoresetevent m_event_received = new autoresetevent ();

// Receiving thread object
Private thread m_thread = NULL;
Protected void startrecivethread (){
// Start the receiving thread
This. m_thread = new thread (this );
This. m_thread.start ();
}

/**
* Thread Functions
*/
Public void run (){
Socketcontainer cc = This. getcontainerclient ();
If (this. m_channel! = NULL)
{
Int nsize = 0;
// Create and allocate a buffer
Bytebuffer BB = bytebuffer. Allocate (this. getbuffersize ());
While (true)
{
// Exit the thread if there is no connection
If (this. m_channel = NULL) break;
Try {
BB. Clear ();
Nsize = This. m_channel.read (bb );
// Sort the buffer to make it available
BB. Flip ();
If (nsize> 0)
{
// Receive data
// Copy the output data block
This. m_receive_data = new byte [nsize];
BB. Get (this. m_receive_data, 0, nsize );
BB. Clear ();
// Set the time mark to notify the thread waiting for acceptance
M_event_received.set ();
If (m_receive_data [6] = 0x00 & m_receive_data [4] =-88 & m_receive_data [5] = 0x0c)
{
If (CC! = NULL)
Cc. freeconnect (this );
System. Out. println ("Close soket ");
}
If (CC! = NULL)
Cc. onreceive (this, this. m_receive_data );

}

} Catch (exception E)
{
// An exception occurs. End the receiving thread.
Cc. freeconnect (this );
System. Out. println ("exception occurred, end receiving thread" + E. getmessage ());
E. printstacktrace ();
Break;
}
}
}

If (CC! = NULL ){
Cc. freeconnect (this );
System. Out. println ("exit and close soket ");
}
This. m_thread = NULL;
System. Out. println ("The socekt receiving thread exits ");

}

Public int send (bytebuffer bb ){
Int nsize = 0;
If (this. m_channel! = NULL )&&
This. m_channel.isconnected ()&&
(BB! = NULL )){
Try {
Nsize = This. m_channel.write (bb );
} Catch (ioexception e ){
E. printstacktrace ();
Nsize = 0;
}
}
Return nsize;
}
Public int send (byte [] array ){
Int nsize = 0;
If (array! = NULL ){
Bytebuffer BB = bytebuffer. Wrap (array );
Nsize = This. Send (bb );
}
Return nsize;
}
Public byte [] getreceivebuff (){
Byte [] DATA = NULL;
If (this. m_channel! = NULL )&&
This. m_channel.isconnected ()){
If (this. m_event_received.waitevent (15000 )){
// Wait until the data
Data = This. m_receive_data;
}
}
Return data;
}

/**
* Socket disconnection event
*/
Public void ondisconnect (){
// Containerclient cc = This. getcontainerclient ();
// If (CC! = NULL ){
// Cc. ondisconnect (this );
//}
}
}

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.