Having problems with your account or logging in?
A lot of changes are happening in the community right now. Some may affect you. READ MORE HERE

Managed COBOL TcpSocket Client Server Communication with sample

Managed COBOL TcpSocket Client Server Communication with sample

Managed COBOL TcpSocket Client Server Communication with sample

There are C# / VB code samples on the MSDN site:
http://msdn.microsoft.com/en-us/library/w89fhyex.aspx
Which show how to use Sockets to enable network communication.
These samples can be used to a write Synchronous Client program and a Synchronous Server Socket Example program.

These communicate which each other synchronously.
This article shows to convert the Microsoft Managed code to Managed Cobol and what the main components are for this to work.

What is a socket.
A socket opens the network connection for the program, allowing data to be read and written over the network. It is important to note that these sockets are software, not hardware.
Please refer to this URL to get a further explanation of the Microsoft .NET Socket Class, URL: http://msdn.microsoft.com/en-us/library/system.net.sockets.socket.aspx

This article focuses around Synchronous communication. There is also a Asynchronous form of communication. All sockets are asynchronous and use a separate thread because of the basic nature of the I/O. But when you just want to receive data from a socket, you can call a receive data method. If the data is not immediately available, then your thread will block. A time out exception will be thrown if you don't receive data within some set time period. At this point, your program can give up or try again. This technique is using sockets synchronously.

Asynchronous. You can poll your sockets for data. If there is no data, it continues. In this case, there is no time out  because you won't call read unless there is actually data waiting for you.

Other major components/technologies used:
You will see most of the code is encapsulated in a try catch block, this helps to handle any potential exceptions that may occur, also this avoids having to wait for long response times if the remote connection cannot be contacted, for example if the remote IP address/host name or Port number cannot be reached, the exception can be handled correctly.


More about the C# to COBOL conversion procedure:

As a starting point to look at converting Code from e.g. Visual Basic or C# to Cobol, you could review the following link in our online documentation:
http://documentation.microfocus.com/help/topic/com.microfocus.eclipse.infocenter.visualcobol.vs/GUID-3C495CA9-2B7A-4890-AC64-005545AED543.html

This section gives examples of how code syntax for the different languages.

Also this article on the codeproject website could be helpful to get yourself familiar:
http://www.codeproject.com/Articles/47571/A-Comparison-Of-net-COBOL-Visual-Basic-and-C

Object-oriented (OO) concepts are fundamental to both .NET and the Java Virtual Machine. If you’re considering deploying COBOL applications onto either platform, you’ll need to have a grounding in OO skills to take full advantage of what these platforms can provide. 
We have produced a guide (available here) that provides an introduction to OO concepts for procedural COBOL developers. We plan to build upon the material, so your feedback on the existing material and the new topics you’d like added is most welcome.

The aim of this demonstration is to show how COBOL .NET Synchronous Socket Server and Client work. The Socket Client sends a message to the Socket Server which returns the received message back to the Socket Client.

Please see below how to use the provided sample code:

Let's start by looking and referring back to this screenshot:
  

-Unzip the included attachment,
-open two Visual COBOL or Enterprise Developer Command prompts,
-In the 1st one launch the Socket Server program, (..\SynchronousServerSocket\bin\Debug\SynchronousServerSocket.exe)
-In the 2nd command prompt launch the socket client, (..\SynchronousSocketClient\bin\Debug\SynchronousSocketClient.exe)
-You should see what is depicted in the two screenshots,

 

 Here are the final C# programs converted to COBOL:

.1) Synchronous Server Socket Example
C#
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class SynchronousSocketClient {

public static void StartClient() {
// Data buffer for incoming data.
byte[] bytes = new byte[1024];

// Connect to a remote device.
try {
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName())
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000);

// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork, 
SocketType.Stream, ProtocolType.Tcp );

// Connect the socket to the remote endpoint. Catch any errors.
try {
sender.Connect(remoteEP);

Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());

// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");

// Send the data through the socket.
int bytesSent = sender.Send(msg);

// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes,0,bytesRec));

// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();

} catch (ArgumentNullException ane) {
Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
} catch (SocketException se) {
Console.WriteLine("SocketException : {0}",se.ToString());
} catch (Exception e) {
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}

} catch (Exception e) {
Console.WriteLine( e.ToString());
}
}

public static int Main(String[] args) {
StartClient();
return 0;
}
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

.2) Synchronous Client Socket Example
C#
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class SynchronousSocketClient {

public static void StartClient() {
// Data buffer for incoming data.
byte[] bytes = new byte[1024];

// Connect to a remote device.
try {
// Establish the remote endpoint for the socket.
// This example uses port 11000 on the local computer.
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName())
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000);

// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetwork, 
SocketType.Stream, ProtocolType.Tcp );

// Connect the socket to the remote endpoint. Catch any errors.
try {
sender.Connect(remoteEP);

Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());

// Encode the data string into a byte array.
byte[] msg = Encoding.ASCII.GetBytes("This is a test<EOF>");

// Send the data through the socket.
int bytesSent = sender.Send(msg);

// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
Console.WriteLine("Echoed test = {0}",
Encoding.ASCII.GetString(bytes,0,bytesRec));

// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();

} catch (ArgumentNullException ane) {
Console.WriteLine("ArgumentNullException : {0}",ane.ToString());
} catch (SocketException se) {
Console.WriteLine("SocketException : {0}",se.ToString());
} catch (Exception e) {
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}

} catch (Exception e) {
Console.WriteLine( e.ToString());
}
}

public static int Main(String[] args) {
StartClient();
return 0;
}
}

 

 

.1) Synchronous Server Socket Example
COBOL .NET

For Cobol imported namespaces:
One difference between the C# / VB and COBOL, the C# Language uses the Import Statement to refer to  certain .NET namespaces, whereas in the COBOL .NET world this is done via the project properties, in this case the following where added:
System.Net
System.Net.Sockets

program-id. SynchronousServerSocket as "ConsoleApplication1.SynchronousServerSocket".

data division.
working-storage section.
01 obj-exception type "Exception".
01 ipHostInfo type "IPHostEntry".
01 ipAddress type "IPAddress".
01 localEndPoint type "IPEndPoint".
01 listener type "Socket". 
01 handler type "Socket". 
78 strSz value 1024.
01 socketData pic x(strSz). 
01 socketDataNetStr type "String". 
01 aChar pic x. 
01 bytes binary-char unsigned occurs strSz.
01 bytesRec binary-long.
01 i binary-long.
01 msg binary-char unsigned occurs strSz.
procedure division.
main.
perform StartListening
stop run.

StartListening.
try
* // Establish the local endpoint for the socket.
* // Dns.GetHostName returns the name of the 
* // host running the application. 
set ipHostInfo to type "Dns"::"Resolve"(type "Dns"::"GetHostName")
set ipAddress to ipHostInfo::AddressList::"Get"(0)
set localEndPoint to new "IPEndPoint"( ipAddress , 11000)

* // Create a TCP/IP socket.
set listener to new "Socket"(
type "AddressFamily"::"InterNetwork" , 
type "SocketType"::"Stream",
type "ProtocolType"::"Tcp")

* // Bind the socket to the local endpoint and 
* // listen for incoming connections. invoke listener::Bind(localEndPoint)
invoke listener::"Bind"(localEndPoint)
invoke listener::Listen(10)

perform until socketData[i :5] = "<EOF>" 
invoke type "Console"::"WriteLine"("Waiting for a connection...")
* // Program is suspended while waiting for an incoming connection.
set handler to listener::"Accept"
initialize socketData aChar
set socketDataNetStr to new "String"(aChar , strSz )

* // An incoming connection needs to be processed. perform until true
set bytesRec to handler::Receive(bytes)
perform varying i from 0 by 1 until i = bytesRec
set socketData[i :1] to type "Encoding"::"ASCII"::"GetString"(bytes , i , bytesRec)
end-perform 
set socketDataNetStr to type "String"::"Concat"(socketDataNetStr::"Substring"(0 , 0 ), type "Encoding"::"ASCII"::"GetString"(bytes , 0 , bytesRec) ) 
exit perform
end-perform

* // Show the data on the console.
invoke type "Console"::"WriteLine"("Text received : {0}", socketData) 
invoke type "Console"::"WriteLine"("Text received : {0}", socketDataNetStr)

* // Echo the data back to the client.
set msg to type "Encoding"::"ASCII"::"GetBytes"(socketData)

invoke handler::Send(msg)
invoke handler::Shutdown(type "SocketShutdown"::"Both")
invoke handler::Close()

catch obj-exception 
display obj-exception
end-try

invoke type "Console"::WriteLine("Press ENTER to continue...")
invoke type "Console"::Read()

.

end program SynchronousServerSocket.

 

 

 


.2) Synchronous Client Socket Example
COBOL .NET

program-id. SynchronousSocketClient as "ConsoleApplication1.SynchronousSocketClient".

data division.
working-storage section.
01 obj-exception type "Exception".
01 ipHostInfo type "IPHostEntry".
01 ipAddress type "IPAddress".
01 remoteEP type "IPEndPoint".
01 sender type "Socket". 
01 msg binary-char unsigned occurs 1024.
01 bytesSent binary-long. 
01 bytesRec binary-long.
01 bytes binary-char unsigned occurs 1024.

procedure division.
main.
perform StartClient
stop run.

StartClient.
try
* // Connect to a remote device 
set ipHostInfo to type "Dns"::"Resolve"(type "Dns"::"GetHostName")
set ipAddress to ipHostInfo::AddressList::"Get"(0)
set remoteEP to new "IPEndPoint"( ipAddress , 11000)

* // Create a TCP/IP socket.
set sender to new "Socket"(
type "AddressFamily"::"InterNetwork" , 
type "SocketType"::"Stream",
type "ProtocolType"::"Tcp")

* // Connect the socket to the remote endpoint. Catch any errors.
invoke sender::Connect(remoteEP)
invoke type "Console"::"WriteLine"("Socket connected to {0}", sender::"RemoteEndPoint"::"ToString")

* // Encode the data string into a byte array.
set msg to type "Encoding"::"ASCII"::"GetBytes"("This is a test<EOF>")

* // Send the data through the socket.
set bytesSent to sender::"Send"(msg)

* // Receive the response from the remote device.
set bytesRec to sender::"Receive"(bytes)

invoke type "System.Console"::"WriteLine"("Echoed test = {0}", type "Encoding"::"ASCII"::"GetString"(bytes , 0 , bytesRec))


* // Release the socket 
invoke sender::Shutdown(type "SocketShutdown"::"Both")
invoke sender::Close()

catch obj-exception 
display obj-exception
end-try
.

end program SynchronousSocketClient.

 

Click here to download the source code:
2465.SynchronousSocketSourceFiles.zip

 

DISCLAIMER:

Some content on Community Tips & Information pages is not officially supported by Micro Focus. Please refer to our Terms of Use for more detail.
Top Contributors
Version history
Revision #:
1 of 1
Last update:
‎2013-06-27 09:24
Updated by:
 
The opinions expressed above are the personal opinions of the authors, not of Micro Focus. By using this site, you accept the Terms of Use and Rules of Participation. Certain versions of content ("Material") accessible here may contain branding from Hewlett-Packard Company (now HP Inc.) and Hewlett Packard Enterprise Company. As of September 1, 2017, the Material is now offered by Micro Focus, a separately owned and operated company. Any reference to the HP and Hewlett Packard Enterprise/HPE marks is historical in nature, and the HP and Hewlett Packard Enterprise/HPE marks are the property of their respective owners.