Socket communication between C++builer and Java

Source: Internet
Author: User
Tags sendmsg

Socket communication between C++builer and Java
C++builer and Java provide a rich socket control/class. This will implement the socket communication between C++builer and Java.
Enables both parties to send information to each other.
In C++builer, we use the ServerSocket control as the server side, Java in the socket class as the client.
This example sends each other as a struct, defined in C++builer as
typedef struct
{
int int1;
float F;
Char ch[20];
Double D;
} tmymsg;

In Java, the sending part is the direct use of the DataOutputStream Writexxx method, of course, can also be converted into byte[with the internal class to send.

The source code is as follows:
C++builer Server Side

Unit1.cpp

//---------------------------------------------------------------------------

#include <vcl.h>
#pragma hdrstop
#include "Unit1.h"
#include <winsock.h>
//---------------------------------------------------------------------------
#pragma package (smart_init)
#pragma resource "*.DFM"
TForm1 *form1;

//---------------------------------------------------------------------------
__fastcall Tform1::tform1 (tcomponent* Owner)
: Tform (Owner)
{
}
//---------------------------------------------------------------------------

void __fastcall Tform1::button1click (tobject *sender)
{
Serversocket1->active = true;
}
//---------------------------------------------------------------------------

void __fastcall Tform1::btnsendclick (tobject *sender)
{
Data to be sent for byte-order conversion.
Tmymsg sendmsg;
Sendmsg.int1 = htonl (30);
SENDMSG.F = NTOHF (12.345);
strcpy (sendmsg.ch, "test data!");
SENDMSG.D = Ntohd (67.890);
Serversocket1->socket->connections[0]->sendbuf (&sendmsg, sizeof (TMYMSG));

}
//---------------------------------------------------------------------------

void __fastcall tform1::formshow (tobject *sender)
{
Memosend->lines->add ("int:30");
Memosend->lines->add ("float:12.345");
Memosend->lines->add ("Char [20]: Test data!");
Memosend->lines->add ("double:67.890");
}
//---------------------------------------------------------------------------

void __fastcall Tform1::serversocket1clientread (TObject *sender,
Tcustomwinsocket *socket)
{
BYTE-order conversion of received data
Tmymsg remsg;
Socket->receivebuf (&remsg,sizeof (tmymsg));
int int1 = Ntohl (remsg.int1);
float f = ntohf (REMSG.F);
Char *ch = new CHAR[20];
strcpy (ch,remsg.ch);
Ansistring sch = Strpas (CH);
Double d = NTOHD (REMSG.D);
delete [] ch;

Memorec->lines->add (INT1);
Memorec->lines->add (f);
Memorec->lines->add (Sch. Trim ());
Memorec->lines->add (d);
}
//---------------------------------------------------------------------------

Unit1.h

//---------------------------------------------------------------------------

#ifndef unit1h
#define UNIT1H
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <ScktComp.hpp>
#pragma pack (1)//byte alignment

//---------------------------------------------------------------------------
typedef struct
{
int int1;
float F;
Char ch[20];
Double D;
} tmymsg;
//---------------------------------------------------------------------------
NTOHF and NTOHD functions for online collection
float NTOHF (float f)
{
unsigned char *p, P0, p1;
if (Ntohs (1) ==1) return F;
p = (unsigned char *) &f;
P0 =p[0];
P1 =p[1];
P[0] =p[3];
P[3] =p0;
P[1] =p[2];
P[2] =P1;
return F;
}
//---------------------------------------------------------------------------
Double Ntohd (double D)
{
unsigned char *p, P0, p1, p2, p3;
if (Ntohs (1) ==1) return D;
p = (unsigned char *) &d;
P0 =p[0];
P1 =p[1];
P2 =p[2];
P3 =P[3];
P[0] =p[7];
P[7] =p0;
P[1] =p[6];
P[6] =P1;
P[2] =p[5];
P[5] =P2;
P[3] =p[4];
P[4] =P3;
return D;
}
//---------------------------------------------------------------------------
Class Tform1:public Tform
{
__published://Ide-managed components
Tserversocket *serversocket1;
TButton *button1;
Tlabel *label1;
TMemo *memosend;
Tlabel *label2;
TMemo *memorec;
TButton *btnsend;
void __fastcall Button1Click (TObject *sender);
void __fastcall Btnsendclick (TObject *sender);
void __fastcall formshow (TObject *sender);
void __fastcall Serversocket1clientread (TObject *sender,
Tcustomwinsocket *socket);
Private://User declarations
Public://User declarations
__fastcall TForm1 (tcomponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *form1;
//---------------------------------------------------------------------------
#endif

Java Client


Import java.awt.*;
Import javax.swing.*;
Import java.awt.event.*;

Import java.io.*;
Import java.net.*;

/*
* Date Created 2006-5-10
*
* TODO to change the template for this generated file, go to the
* Windows-Preferences-Java-code styles-code templates
*/

/**
* @author ZWX
*
* TODO to change the template for this generated type annotation, go to the window-preferences-Java-code style-code template
*/
public class Socketclientdemo extends JFrame {
int port = 2345;
String host = "localhost";
Socket socket;
JButton jbconnect = new JButton ("Connection");
JButton jbsend = new JButton ("send");
JTextArea jtasend = new JTextArea (7, 10);
JTextArea Jtarec = new JTextArea (7, 10);

Public Socketclientdemo () {
Super ("Client");
Container CP = This.getcontentpane ();
Cp.setlayout (New FlowLayout ());
Cp.add (Jbconnect);
Cp.add (Jbsend);
Jbsend.addactionlistener (Jbsendal); Send button
Jbconnect.addactionlistener (jbconnectal); Connection button


Cp.add (JTAREC);
Jtarec.append ("received content");
Cp.add (Jtasend);
Jtasend.append ("Sent content");
Jtasend.append ("/nint:88");
Jtasend.append ("/nfloat:77.66");
Jtasend.append ("/nstring:from JAVA");
Jtasend.append ("/ndouble:23.45");

This.setsize (250, 200);
This.setlocation (100, 100);
This.setdefaultcloseoperation (Jframe.exit_on_close);
This.setvisible (TRUE);

}

public static void Main (string[] args) {
New Socketclientdemo ();
}

ActionListener jbconnectal = new ActionListener () {

public void actionperformed (ActionEvent e) {
try {
Instantiate the socket and receive data sent from the C++builder server side
Socket = new Socket (Inetaddress.getbyname (host), Port);
DataInputStream in = new DataInputStream (socket. getInputStream ());
int int1 = In.readint ();
float f = in.readfloat ();
byte[] buffer = new BYTE[20];
In.read (buffer);
String ch = new string (buffer);
Double d = in.readdouble ();

Jtarec.append ("n" + integer.tostring (int1));
Jtarec.append ("n" + float.tostring (f));
Jtarec.append ("n" + Ch.trim ());
Jtarec.append ("n" + double.tostring (d));
}//try
catch (IOException ex) {
Ex.printstacktrace ();
}

}

};

ActionListener jbsendal = new ActionListener () {

public void actionperformed (ActionEvent e) {
try {
Send to server side
DataOutputStream out = new DataOutputStream (Socket.getoutputstream ());

int int1 = 88;
float f = (float) 77.66;
String ch = "from JAVA";
Double d = 23.45;

Out.writeint (INT1);
Out.writefloat (f);
byte[] buf = new BYTE[20];
System.arraycopy (Ch.getbytes (), 0,buf,0,ch.length ());
Out.write (buf,0,buf.length);
Out.writedouble (d);

}//try
catch (IOException ex) {
Ex.printstacktrace ();
}

}

};

}

Due to the sequence of data storage of the program of the C + + language is related to the CPU of compiling the platform machine, the Java program adopts large byte sequence, and the network byte order is also stored in large byte order,
Therefore, the sending and receiving functions of C++builer must first convert the data into byte order. Also note the byte alignment problem, in this case the C++builder structure is one byte alignment.
The running interface is as follows:


When running, start the server side first, click the "Start Server Side" button. Then start the client, select the connection, first send the server data, and then send the client data. Close the server side first when shutting down.

If you have any questions, please correct me. E-mail:weixing979@163.com

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.