SocketException was caught - c#

My code
This code for server
class Program
{
private static readonly byte[] Localhost = {127,0,0,1};
private const int Port = 8567;
static void Main(string[] args)
{
var address = new IPAddress( Localhost );
var endPoint = new IPEndPoint(address, Port);
var listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
listener.Bind(endPoint);// Error in this line
listener.Listen(3);
String data = "";
while (true)
{
Console.WriteLine("Listening on sport {0}", endPoint);
byte[] buffer = new byte[4096];
// handle incoming connection ...
var handler = listener.Accept();
Console.WriteLine("Handling incoming connection ...");
while (true)
{
int count = handler.Receive(buffer);
data += Encoding.UTF8.GetString(buffer, 0, count);
// Find start of MLLP frame, a VT character ...
int start = data.IndexOf((char) 0x0B);
if (start >= 0)
{
// Now look for the end of the frame, a FS character
int end = data.IndexOf((char) 0x1C);
if (end > start)
{
string temp = data.Substring(start + 1, end - start);
// handle message
string response = HandleMessage(temp);
// Send response
handler.Send(Encoding.UTF8.GetBytes(response));
break;
}
}
}
// close connection
handler.Shutdown( SocketShutdown.Both);
handler.Close();
Console.WriteLine("Connection closed.");
}
}
catch (Exception e)
{
Console.WriteLine("Exception caught: {0}", e.Message);
}
Console.WriteLine("Terminating - press ENTER");
Console.ReadLine();
}
private static string HandleMessage(string data)
{
Console.WriteLine("Received message");
var msg = new Message();
msg.Parse(data);
Console.WriteLine("Parsed message : {0}", msg.MessageType() );
Console.WriteLine("Message timestamp : {0}", msg.MessageDateTime() );
Console.WriteLine("Message control id : {0}", msg.MessageControlId());
// *********************************************************************
// Here you could do something usefull with the received message ;-)
// *********************************************************************
// todo
// Create a response message
//
var response = new Message();
var msh = new Segment("MSH");
msh.Field(2, "^~\\&");
msh.Field(7, DateTime.Now.ToString("yyyyMMddhhmmsszzz"));
msh.Field(9, "ACK");
msh.Field(10, Guid.NewGuid().ToString() );
msh.Field(11, "P");
msh.Field(12, "2.5.1");
response.Add(msh);
var msa = new Segment("MSA");
msa.Field(1, "AA");
msa.Field(2, msg.MessageControlId());
response.Add(msa);
// Put response message into an MLLP frame ( <VT> data <FS><CR> )
//
var frame = new StringBuilder();
frame.Append((char) 0x0B);
frame.Append(response.Serialize());
frame.Append( (char) 0x1C);
frame.Append( (char) 0x0D);
return frame.ToString();
}
}
but I am getting following error:
SocketException was caught :- An attempt was made to access a socket in a way forbidden by its access permissions
Please give me any solution.

Exception message tells that you don't have access rights to the socket you created. This can be caused by either socket being already used or user running this process having lower rights than necessary (non-admin rights; this is less likely the reason of the exception in your case).
To check whether some process is already using the socket, open Command Prompt and execute:
netstat -o | find "8567"

Related

TCP Connection keep disconnecting with Analyzer Mindray BS240

I'm working on a TCP communication program for the chemestry analyzer "Mindray BS240". The problem is that the analyzer keep disconnecting and reconnecting (every 30s). Here is my code, what did I miss ?
private void startTcpListner()
{
try
{
var port = settings.LisPort;
IPAddress localAddr = IPAddress.Parse(settings.LisIpAddress);
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
var bytes = new byte[256];
String data = null;
LogManager.GetCurrentClassLogger().Info("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also use server.AcceptSocket() here.
var client = server.AcceptTcpClient();
LogManager.GetCurrentClassLogger().Info("Connected !");
data = null;
// Get a stream object for reading and writing
stream = client.GetStream();
// Enter the listening loop.
while (true)
{
while (!stream.DataAvailable) ;
int i;
// Loop to receive all the data sent by the client.
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
// Translate data bytes to a ASCII string.
var line = Encoding.UTF8.GetString(bytes, 0, i);
LogManager.GetCurrentClassLogger().Info("Received: {0}", line);
data += line;
if (line.Length > 3 &&
line[line.Length - 2] == Hl7Helper.FileSeparator &&
line[line.Length - 1] == Hl7Helper.CarriageReturn)
{
handleMessage(data);
data = null;
}
}
}
}
catch (SocketException e)
{
LogManager.GetCurrentClassLogger().Error("SocketException: {0}", e);
}
catch (Exception e)
{
LogManager.GetCurrentClassLogger().Error(e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
}
In the log file, I have :
Waiting for a connection...
Connected !

C# client socket multiple send and receive

I am using sockets for TCP-IP connection and I would like to establish simple system send-receive from the client side.
Socket sck;
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndpt = new IPEndPoint(IPAddress.Parse("123.123.123.1"), 12345);
try
{
sck.Connect(localEndpt);
}
catch
{
Console.Write("Unable to Connect");
}
while (true)
{
Console.WriteLine("Enter Text");
string sendtext = Console.ReadLine();
byte[] Data = Encoding.ASCII.GetBytes(sendtext);
sck.Send(Data);
Console.WriteLine("Data Sent!");
byte[] bytesReceived = new byte[sck.ReceiveBufferSize];
int bytes = 0;
String strReceived = "";
int dataAvailable = 0;
while (dataAvailable == 0 || dataAvailable != sck.Available)
{
dataAvailable = sck.Available;
Thread.Sleep(100); // if no new data after 100ms assume transmission finished
}
if (sck.Available > 0)
{
bytes = sck.Receive(bytesReceived, bytesReceived.Length, 0);
strReceived+=Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
Console.WriteLine("Received from server: " + strReceived);
}
Console.Read();
The problem is that first requests goes throught but the second does not, because socket is not available anymore (socket "Availabe" attribute value is 0). What am I doing wrong? What would be the easiest way to establish multiple send-recieve requests (in order)?
This code works fine for me
private List<Socket> _clients = new List<Socket>();
private Thread _dataReceiveThread;
private bool _isConnected;
private void DataReceive()
{
while (_isConnected)
{
List<Socket> clients = new List<Socket>(_clients);
foreach (Socket client in clients)
{
try
{
if (!client.Connected) continue;
string txt = "";
while (client.Available > 0)
{
byte[] bytes = new byte[client.ReceiveBufferSize];
int byteRec = client.Receive(bytes);
if (byteRec > 0)
txt += Encoding.UTF8.GetString(bytes, 0, byteRec);
}
if (!string.IsNullOrEmpty(txt))
/* TODO: access the text received with "txt" */
}
catch (Exception e)
{
Exception_Handler(e);
}
}
}
}
Just run this code to get started
_isConnected = true;
_dataReceiveThread = new Thread(DataReceive);
_dataReceiveThread.Start();
Update list box in Cross thread:
This code can be placed in the comment section.
myListBox1.Invoke((Action)(() => { myListBox1.Items.Add(txt) }));
Socket. Available does NOT indicate whether the socket is available, but incoming data is available for reading:
https://msdn.microsoft.com/en-us/library/ee425135.aspx
Your program quits because it checks for a reply (incoming data) immediately after sending a message out. Use a Thread.Sleep before checking for data.
Maybe the message has not even been sent, because Socket.Send just places it in the network interface card's output buffer. When the socket finally sends the message, it will upare the connection state. If it got no reply (on a TCP connection), it will tell you that it is disconnected when you query the state. On UDP it will tell you nothing, because UDP is connectionless.

C# TcpClient "The operation is not allowed on non-connected sockets."

My goal is to create a TcpClient that stays connected, allowing messages to be sent to the server, as well as having a timed monitor that sends a special message to the server during a certain idle frequency. Haven't made it too far before getting stumped.
With the current code, the first message sent using a console tester app receives fine, but upon sending another an exception is thrown with the message "The operation is not allowed on non-connected sockets."
I have tried removing the stream.Dispose() line and it will hang on stream.Read(...) during the second attempt. I have also tried making NetworkStream stream a member of the class and set it to client.GetStream() in the constructor and it will hang on stream.Read(...) during the second attempt.
public class TcpClientTest
{
private TcpClient client = new TcpClient();
private string hostName;
private int port;
public TcpClientTest(string hostName, int port)
{
this.hostName = hostName;
this.port = port;
client.Connect(hostName, port);
}
public byte[] SendMessage(string name, string message)
{
if (client == null) throw new Exception("Client connection has not been established");
Person person = new Person();
person.Name = name; person.Message = message;
byte[] messageBytes = (System.Text.Encoding.Unicode.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(person)));
const int bytesize = 1024 * 1024;
try
{
NetworkStream stream = client.GetStream();
if (stream != null)
{
stream.Write(messageBytes, 0, messageBytes.Length); // Write the bytes
messageBytes = new byte[bytesize]; // Clear the message
// Receive the stream of bytes
stream.Read(messageBytes, 0, messageBytes.Length);
}
// Clean up
stream.Flush();
stream.Dispose();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
return messageBytes; // Return response
}
}
// In console tester app
static void Main(string[] args)
{
TcpClientTest client = new TcpClientTest("127.0.0.1", 1234);
string exit = "2";
do
{
if (exit == "1") client.SendMessage("TEST", "TEST");
Console.WriteLine("1 Send Message 2 Exit");
exit = Console.ReadLine();
} while (exit != "2");
}

Server refuses to accept requests from clients

This is a program to search for strings from a file. The string required by the client is given from the client side, in my case, using telnet. The program I have written is a server side one. It accepts multiple clients.
But, the problems I am unable rectify are-
It doesn't check for strings from the file.
As soon as the client gets connected, the client cannot type in the strings they want to search in that particular file.
It doesn't send the reply back (i.e. If the string is present in the file or not) to the client. Its only shown on the server side.
How do I proceed further? Could someone tell me where am I going wrong? Could someone please help me out with the code?
This is my try at the program..
class Program
{
static void Main(string[] args)
{
IPAddress ipad = IPAddress.Parse("192.168.0.181");
TcpListener serversocket = new TcpListener(ipad, 8888);
TcpClient clientsocket = default(TcpClient);
Byte[] bytes = new Byte[256];
serversocket.Start();
Console.WriteLine(">> Server Started");
while(true)
{
clientsocket = serversocket.AcceptTcpClient();
Console.WriteLine("Accepted Connection From Client");
LineMatcher lm = new LineMatcher(clientsocket);
Thread thread = new Thread(new ThreadStart(lm.Run));
thread.Start();
Console.WriteLine("Client connected");
}
Console.WriteLine(" >> exit");
Console.ReadLine();
clientsocket.Close();
serversocket.Stop();
}
}
public class LineMatcher //I've jumbled it up here. Don't know what exactly to do..
{
public string fileName = "c:/myfile2.txt";
private TcpClient _client;
public LineMatcher(TcpClient client)
{
_client = client;
}
public void Run()
{
try
{
StreamReader sr = new StreamReader("c:/myfile2.txt");
using (var reader = new StreamReader(_client.GetStream()))
{
string line ="";
int lineNumber = 0;
while (null != (line = sr.ReadLine()))
{
lineNumber += 1;
byte[] data = new byte[1024];
NetworkStream stream = _client.GetStream();
//if (line.Equals(line))
for (int ct = stream.Read(data,0, data.Length-1); 0 < ct; ct = stream.Read(data,0,data.Length-1))
line += Encoding.ASCII.GetString(data, 0, ct);
line = line.Trim();
{
lineNumber.ToString();
data = Encoding.ASCII.GetBytes(line);
_client.Client.Send(data, data.Length, SocketFlags.None);
Console.WriteLine("Line {0} matches {1}", lineNumber, line);
}
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.ToString());
}
Console.WriteLine("Closing client");
_client.Close();
}
}
I think you got some pieces in your Run-method swapped - here is a version that should do the job:
public void Run()
{
byte[] data;
try
{
using (var r = new StreamReader("c:/myfile2.txt"))
{
string line ="";
int lineNumber = 0;
while (null != (line = r.ReadLine()))
{
data = Encoding.ASCII.GetBytes(line + "\n");
_client.Client.Send(data, data.Length, SocketFlags.None);
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.ToString());
}
Console.WriteLine("Closing client");
_client.Close();
}
Please note that I'm not 100% sure what you are trying to do (I think you want your textfile send line-by-line to your Terminal) - so you might have to change some bits here and there.
Don't know where the Stream-messes in your code came from but I guess you tried various tutorials/snippets and forgot to clean up ;)

Problem with simple tcp\ip client-server

i'm trying to write simple tcp\ip client-server.
here is server code:
internal class Program
{
private const int _localPort = 7777;
private static void Main(string[] args)
{
TcpListener Listener;
Socket ClientSock;
string data;
byte[] cldata = new byte[1024];
Listener = new TcpListener(_localPort);
Listener.Start();
Console.WriteLine("Waiting connections [" + Convert.ToString(_localPort) + "]...");
try
{
ClientSock = Listener.AcceptSocket();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return;
}
int i = 0;
if (ClientSock.Connected)
{
while (true)
{
try
{
i = ClientSock.Receive(cldata);
}
catch
{
}
try
{
if (i > 0)
{
data = Encoding.ASCII.GetString(cldata).Trim();
ClientSock.Send(cldata);
}
}
catch
{
ClientSock.Close();
Listener.Stop();
Console.WriteLine(
"Server closing. Reason: client offline. Type EXIT to quit the application.");
}
}
}
}
}
And here is client code:
void Main()
{
string data; // Юзерская дата
byte[] remdata ={ };
TcpClient Client = new TcpClient();
string ip = "127.0.0.1";
int port = 7777;
Console.WriteLine("\r\nConnecting to server...");
try
{
Client.Connect(ip, port);
}
catch
{
Console.WriteLine("Cannot connect to remote host!");
return;
}
Console.Write("done\r\nTo end, type 'END'");
Socket Sock = Client.Client;
while (true)
{
Console.Write("\r\n>");
data = Console.ReadLine();
if (data == "END")
break;
Sock.Send(Encoding.ASCII.GetBytes(data));
Sock.Receive(remdata);
Console.Write("\r\n<" + Encoding.ASCII.GetString(remdata));
}
Sock.Close();
Client.Close();
}
When i'm sending to my server i cannt receive data back answer. Sock.Receive(remdata) returns nothing! Why?
You're trying to receive to an empty buffer. You should allocate the buffer with a sensible size, and then take note of the amount of data received:
byte[] buffer = new byte[1024];
...
int bytesReceived = socket.Receive(buffer);
string text = Encoding.ASCII.GetString(buffer, 0, bytesReceived);
(It's somewhat unconventional to use PascalCase for local variables, by the way. I'd also urge you not to just catch Exception blindly, and not to swallow exceptions without logging them.)

Categories