Socket losses connection after "Socket.Receive" function - c#

I have a c# client. The client's task is to log in to the server.
The issue is:
When I want to log in, I use a TCP socket which is created when the "wpf" window is initialized. After sending data using the socket once, everything is ok but when I want to send data again, using the same socket, this exception pops up:
System.ObjectDisposedException: 'Cannot access a disposed object.
Object name: 'System.Net.Sockets.Socket'.'
After some testing, I found out that the problem is caused by the Socket.Receive function. I checked the socket before the function was called, and the socket was connected (Socket.Connected == true), after returning from the function, the socket wasn't connected (Socket.Connected == false)
private static Socket ConnectSocket(string server, int port)
{
Socket s = null;
// Get host related information.
IPHostEntry hostEntry = Dns.GetHostEntry(server);
// Loop through the AddressList to obtain the supported AddressFamily.
foreach (IPAddress address in hostEntry.AddressList)
{
//attempting to connect.
IPEndPoint ipe = new IPEndPoint(address, port);
//making a temp socket to check the connection (if something went wronge/ the server isnt active)
Socket tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
// attempting connection.
tempSocket.Connect(ipe);
}
catch (Exception)
{
Console.WriteLine("Request timed out");
}
//if we connected to the server, we are ok to continue.
if (tempSocket.Connected)
{
s = tempSocket;
break;
}
//else the connection isnt successful (the server might not respond) we need to try again.
else
{
continue;
}
}
Globals.SOCKET = s;
return s;
}
//This func will send a request to the server and returns the server's response.
public static string SocketSendReceive(string server, int port, string request, Socket socket = null)
{
Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
Byte[] bytesReceived = new Byte[256];
string response = "";
// Create a socket connection with the specified server and port.
if (socket == null)
socket = ConnectSocket(server, port);
using (socket)
{
// If the connection faild and couldnt maintain a socket.
if (socket.Connected == false)
return ("Connection failed");
// Send request to the server.
socket.Send(bytesSent, bytesSent.Length, 0);
// Receiving the packet from the server.
int bytes = socket.Receive(bytesReceived, bytesReceived.Length,0);//***The problem occures Here***
response = response + Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
return response;
}
the second function is the one that sends and receives data from the server.
the first one is just connecting and creating a socket
Thanks for your help!
-Anthon

Change
socket.Receive(bytesReceived, bytesReceived.Length,0)
To
socket.Receive(bytesReceived, 0, bytesReceived.Length)

Related

Socket Programming in C# Is this considered polling?

so I have been trying out socket programming in C# using code found online. When looking at this code from https://www.geeksforgeeks.org/socket-programming-in-c-sharp/
public static void ExecuteServer()
{
// Establish the local endpoint
// for the socket. Dns.GetHostName
// returns the name of the host
// running the application.
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 11111);
// Creation TCP/IP Socket using
// Socket Class Costructor
Socket listener = new Socket(ipAddr.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try {
// Using Bind() method we associate a
// network address to the Server Socket
// All client that will connect to this
// Server Socket must know this network
// Address
listener.Bind(localEndPoint);
// Using Listen() method we create
// the Client list that will want
// to connect to Server
listener.Listen(10);
while (true) {
Console.WriteLine("Waiting connection ... ");
// Suspend while waiting for
// incoming connection Using
// Accept() method the server
// will accept connection of client
Socket clientSocket = listener.Accept();
// Data buffer
byte[] bytes = new Byte[1024];
string data = null;
while (true) {
int numByte = clientSocket.Receive(bytes);
data += Encoding.ASCII.GetString(bytes,
0, numByte);
if (data.IndexOf("<EOF>") > -1)
break;
}
Console.WriteLine("Text received -> {0} ", data);
byte[] message = Encoding.ASCII.GetBytes("Test Server");
// Send a message to Client
// using Send() method
clientSocket.Send(message);
// Close client Socket using the
// Close() method. After closing,
// we can use the closed Socket
// for a new Client Connection
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
}
catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
}
}
I was wondering if the portion
while (true) {
int numByte = clientSocket.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, numByte);
if (data.IndexOf("<EOF>") > -1)
break;
}
is considered a polling method and also reason why we do not simply use
int numByte = clientSocket.Receive(bytes);
data = Encoding.ASCII.GetString(bytes, 0, numByte);
I have tried the above and it seems to work just as fine. So is there a reason why we use a infinite while loop that depends on the text to stop reading? I have found many sources which seems to use this method. Why is this so?

Sockets not able to receive message from the server

I am trying to connect to a application using sockets.
The application communicates using port 6100.
I am am able to send the messages to the application but not able to receive any message.
This is my code please let me know if i am doing anything wrong.
public void Connect2(string host, int port, string cmd)
{
byte[] bytes = new byte[10024];
IPAddress[] IPs = Dns.GetHostAddresses(host);
Socket s = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
s.SendTimeout = 100;
Console.WriteLine("Establishing Connection to {0}",
host);
try
{
s.Connect(IPs[0], port);
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
byte[] sendBites = System.Text.Encoding.ASCII.GetBytes(cmd);
int bytesSent = s.Send(sendBites);
int bytesRec = s.Receive(bytes);
s.ReceiveFrom(bytes, ref tmpRemote);
MessageBox.Show(s.ReceiveBufferSize.ToString());
MessageBox.Show(Encoding.ASCII.GetString(bytes, 0, bytesRec));
s.Shutdown(SocketShutdown.Both);
s.Close();
}
First when the Connect failes, you're still trying to send/receive data. Put the send and receive inside the try/catch.
I can see that you're calling receive twice:
int bytesRec = s.Receive(bytes);
s.ReceiveFrom(bytes, ref tmpRemote);
What probably happens is:
You are sending a command
You are waiting for a response "int bytesRec = s.Receive(bytes);"
Then again you are waiting for more data.. "s.ReceiveFrom(bytes, ref tmpRemote);"
But probably the server won't send additional data, so you are waiting "forever"
Try again removing the s.ReceiveFrom(bytes, ref tmpRemote);
The Socket.ReceiveFrom() is usually used for receiving UDP broadcasts.
This piece of code works fine.
public string SocketSendReceive(string server, int port, string cmd)
{
byte[] recvBuffer = new byte[1024];
string host = "127.0.0.1";
TcpClient tcpClient = new TcpClient();
try
{
tcpClient.Connect(host, 6100);
}
catch (SocketException /*e*/)
{
tcpClient = null;
}
if (tcpClient != null && tcpClient.Connected)
{
tcpClient.Client.Send(Encoding.UTF8.GetBytes(cmd));
tcpClient.Client.Receive(recvBuffer);
// port = Convert.ToInt16(Encoding.UTF8.GetString(recvBuffer).Substring(2));
tcpClient.Close();
}
return Encoding.ASCII.GetString(recvBuffer, 0, recvBuffer.Length);
}

TCP connection timeout error code _COMPlusExceptionCode -532462766

I am a Newbie to TCP/IP programming in c#, so I am DESPERATE for a solution to my current problem!
I have designed a C# Windows application running under Windows 7 with a Sqlserver 2005 database. My application is trying to send an HL7 record over a TCP/IP connection, to a Unix Lab. system machine.
I can get a connection ok, and send the HL7. BUT I cannot get ANY reply from the Lab. server! the connection times-out with error code 10060, as well as a _COMPlusExceptionCode value of -532462766.
Here is a sample of my c# 'Connect' methods:
buildSendHL7_TCPIP hl7Agent = new buildSendHL7_TCPIP();
// class 'buildSendHL7_TCPIP(); ' contains methods to build the HL7 segments, as well as methods to send and receive messages over the TCP connection
string strServerIPAddress = string.Empty;
Int32 intSocketNo = new Int32();
bool sentOK = false;
/***********************************/
/*Try send the HL7 to LIS-HORIZON...*/
/***********************************/
strServerIPAddress = "10.1.6.248";
intSocketNo = 5910;
sentOK = hl7Agent.SendHL7(strServerIPAddress, intSocketNo, strHL7_Record);
if (!sentOK)
{
_strUIMessage = "*Error* HL7 Message NOT sent to LIS!";
opsMessageBox mb = new opsMessageBox(this);
mb.ShowDialog();
mb.Close();
goto EndLabel;
}
Here are the methods I've created to build a TCP connection and send the HL7 to the LIS Server:
public bool SendHL7(string strIPAddress, Int32 intSocket, string hl7message)
{
/* send the complete HL7 message to the server...*/
int port = (int)intSocket;
IPAddress localAddr = IPAddress.Parse(strIPAddress);
try
{
// Add the leading & trailing character field-separator and CR LineFeed' t.
string llphl7message = null;
llphl7message = "|";
llphl7message += hl7message;
llphl7message += Convert.ToChar(28).ToString();
llphl7message += Convert.ToChar(13).ToString();
// Get the size of the message that we have to send.
Byte[] bytesToSend = Encoding.ASCII.GetBytes(llphl7message);
Byte[] bytesReceived = new Byte[256];
// Create a socket connection with the specified server and port.
Socket s = ConnectSocket(localAddr, port);
// If the socket could not get a connection, then return false.
if (s == null)
return false;
// Send message to the server.
s.Send(bytesToSend, bytesToSend.Length, 0);
// Receive the response back
int bytes = 0;
s.ReceiveTimeout = 3000; /* 3 seconds wait before timeout */
bytes = s.Receive(bytesReceived, bytesReceived.Length, 0); /* IMEOUT occurs!!! */
string page = Encoding.ASCII.GetString(bytesReceived, 0, bytes);
s.Close();
// Check to see if it was successful
if (page.Contains("MSA|AA"))
{
return true;
}
else
{
return false;
}
}
catch (SocketException e)
{
MessageBox.Show("SocketExecptionError:" + e);
return false;
}
}
private static Socket ConnectSocket(IPAddress server, int port)
{
Socket s = null;
IPHostEntry hostEntry = null;
// Get host related information.
hostEntry = Dns.GetHostEntry(server);
foreach (IPAddress address in hostEntry.AddressList)
{
IPEndPoint ipe = new IPEndPoint(address, port);
Socket tempSocket = new Socket(ipe.AddressFamily,SocketType.Stream,ProtocolType.Tcp);
tempSocket.Connect(ipe);
if (tempSocket.Connected)
{
s = tempSocket;
break;
}
else
{
continue;
}
}
return s;
}
I've been told that socket 5910 cannot receive ANY communications in Windows 7 due to Virus issues. Is this true? If so, I tried to connect to ANOTHER server on our network (PACS/RIS) socket # 5556. I get the SAME timeout error message.
The behaviour looks like the server doesn't understand your request / doesn't recognize it as a complete message according to the expected protocol.
As I understand from your code you are sending a HL7 message. I don't know this protocol, according to google it could be Health Level 7. The example I found is starting with some text, then a | as a delimiter. Your message is starting with |. Maybe there is the problem...
So you should have a look if the message you send is matching the protocol definition.

Cannot access a disposed object. in c# client & Server

I had fix my Problem Cannot access a disposed object. in c# client & Server
Following Points I Used.
Used Using for Scope Limitation
i am not Closed Socket Object
class Client
{
static void Main(string[] args)
{
Console.Title = "Client Chat";
byte[] bytes = new byte[1024];// data buffer for incoming data
string data = null;
// connect to a Remote device
try
{
// Establish the remote end point for the socket
IPHostEntry ipHost = Dns.Resolve("localhost");
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 95);
using (Socket Socketsender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
Socketsender.Connect(ipEndPoint);
Console.WriteLine("\n\n\tSocket Connecting To Java Server...." + Socketsender.RemoteEndPoint.ToString());
while (true)
{
Console.Write("\n\n\tClient::");
string theMessage = Console.ReadLine();
byte[] msg = Encoding.ASCII.GetBytes(theMessage);
// Send the data through the socket
int bytesSent = Socketsender.Send(msg);
//Recieved from Java Server Message
int bytesRec = Socketsender.Receive(bytes);
Console.WriteLine("\n\n\tJava Server Says:: {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));
}
//Socketsender.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
You create your Socket handler object outside the loop and close it inside the loop. The second pass through your loop you are looking at a Socket object that you have already closed.
Don't close your Socket until you are finished with it.

in c# getting Error cannot access a disposed object object name='System.Net.Socket.Socket'

I want a chat application in C# Client and in Java Server
I go through C# Client but I got some Error when I response to Java Server I get the error#
cannot access a disposed object object name='System.Net.Socket.Socket'
class Program
{
static void Main(string[] args)
{
byte[] bytes = new byte[1024];// data buffer for incoming data
// connect to a Remote device
try
{
// Establish the remote end point for the socket
IPHostEntry ipHost = Dns.Resolve("localhost");
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 95);
Socket Socketsender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint
Socketsender.Connect(ipEndPoint);
Console.WriteLine("\n\n___________________Client Server Chat Application__________________________");
Console.WriteLine("___________________________________________________________________________");
Console.WriteLine("\nSocket Connecting To Java Server...." + Socketsender.RemoteEndPoint.ToString());
// Console.ReadLine();
string data = null;
while (true)
{
//Recieved from Java Server Message
int bytesRec = Socketsender.Receive(bytes);
Console.WriteLine("\nJava Server:: {0}", Encoding.ASCII.GetString(bytes, 0, bytesRec));
// Console.ReadLine();
Console.Write("C# Client ::"); // Prompt
string line = Console.ReadLine();
byte[] sendToServer = Encoding.ASCII.GetBytes(line);
// Send the data through the socket
int intByteSend = Socketsender.Send(sendToServer);
// Socketsender.Shutdown(SocketShutdown.Both);
Socketsender.Close();
Console.WriteLine("____________________________________________________________________________");
Console.WriteLine("_________________________End Chat___________________________________________");
// Socketsender.Shutdown(SocketShutdown.Both);
Socketsender.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
You are closing your socket (Socketsender) in he while loop, and then—in the next iteration—calling Receive on it.
Once a socket is closed it is dead,1 and cannot be used for anything. You would need to create a new socket and connect it to the server.
Or better, keep the first socket open.
(You also are performing the close twice, but I'm assuming that is a transcription error.)
1 Insert dead parrot here.

Categories

Resources