My problem is weird and i was not able to find a resolution from referring to other threads regarding this. I am getting the error when i run the microsoft Synchronous Server Socket Example, Synchronous Client Socket Example, on two systems which are part of the domain but i do not get this error when i run the same code on two systems which are part of the network but they are not part of the domain! Anyone know what might be causing the issue?
The things i have done to try to resolve are I made sure the port was open, switched off the firewall and antivirus as suggested by others with similar problem.But it has not helped.
Server code:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SynchronousSocketListener {
// Incoming data from the client.
public static string data = null;
public static void StartListening() {
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp );
// Bind the socket to the local endpoint and
// listen for incoming connections.
try {
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true) {
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
data = null;
// An incoming connection needs to be processed.
while (true) {
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes,0,bytesRec);
if (data.IndexOf("<EOF>") > -1) {
break;
}
}
// Show the data on the console.
Console.WriteLine( "Text received : {0}", data);
// Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static int Main(String[] args) {
StartListening();
return 0;
}
}
Client Code::
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.
IPAddress ipAddress = IPAddress.Parse("172.21.98.122");//Server IP
IPEndPoint remoteEP = new IPEndPoint(ipAddress,11000);
// Create a TCP/IP socket.
Socket sender = new Socket(ipAddress.AddressFamily,
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;
}
}
Related
i want to let 2 c# apps each one is on a separate computer and both connected to the same ADSL router to send messages to each other i know that we have to use Sockets and tried many solutions on the internet but they are all working at the same computer but not working on a separate computers.
i believe that the problem is in the ip addresses but i tried a lot with no good results
is there any simple code to help please
i tried this function on server side
public static void StartServer()
{
IPHostEntry host = Dns.GetHostEntry("DESKTOP-SBJHC7I");
IPAddress ipAddress = host.AddressList[0];
Console.WriteLine(ipAddress.ToString());
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
try
{
// Create a Socket that will use Tcp protocol
Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
// A Socket must be associated with an endpoint using the Bind method
listener.Bind(localEndPoint);
// Specify how many requests a Socket can listen before it gives Server busy response.
// We will listen 10 requests at a time
listener.Listen(10);
Console.WriteLine("Waiting for a connection...");
Socket handler = listener.Accept();
// Incoming data from the client.
string data = null;
byte[] bytes = null;
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
Console.WriteLine("Text received : {0}", data);
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\n Press any key to continue...");
Console.ReadKey();
}
and this function in the client side
public static void StartClient()
{
byte[] bytes = new byte[1024];
try
{
// Connect to a Remote server
// Get Host IP Address that is used to establish a connection
// In this case, we get one IP address of localhost that is IP : 127.0.0.1
// If a host has multiple addresses, you will get a list of addresses
IPHostEntry host = Dns.GetHostEntry("DESKTOP-SBJHC7I");
IPAddress ipAddress = host.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket sender = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
// Connect to Remote EndPoint
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());
}
}
please make sure that your client is connected to the same IP on which server is started. because it seems in your code that your client connecting to host which you getting it from localhost identity. For your testing purpose please hardcode the Server's IP address in your Remoteendpoint. if still the issue same then I will share code to test on a different networks.
Any help on the issue below would be highly appreciated. I'm using the StreamSocketListener Class to accept TCP/IP connection on my Raspberry Pi 3 running windows IoT 10 Core.
This is my server code so far:
static string _maintenancePort = "8888";
public async static void StartListening()
{
try
{
StreamSocketListener listener = new StreamSocketListener();
var currentSetting = listener.Control.QualityOfService;
listener.Control.QualityOfService = SocketQualityOfService.LowLatency;
listener.ConnectionReceived += SocketListener_ConnectionReceived;
listener.Control.KeepAlive = true;
await listener.BindServiceNameAsync(_maintenancePort);
}
catch (Exception e)
{
Log.WriteErrorLog(e);
}
}
private static async void SocketListener_ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
try
{
Log.WriteDebugLog("Incoming data...");
Stream inStream = args.Socket.InputStream.AsStreamForRead();
StreamReader reader = new StreamReader(inStream);
string request = await reader.ReadLineAsync();
if (request != null)
{
Log.WriteDebugLog("Received : " + request);
}
}
catch (Exception e)
{
Log.WriteErrorLog(e);
}
}
I wrote the following client code to connect to the socket. This code runs on another machine.
// ManualResetEvent instances signal completion.
private static ManualResetEvent connectDone = new ManualResetEvent(false);
private static ManualResetEvent sendDone = new ManualResetEvent(false);
private static ManualResetEvent receiveDone = new ManualResetEvent(false);
private static String response = String.Empty;
public static Socket client;
public static string SendMessageToClient(string ip, int port, string message, bool expectResponse)
{
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
IPAddress ipAddress = IPAddress.Parse(ip);
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
client = new Socket(ipAddress.AddressFamily,SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
message += "^" + expectResponse.ToString();
// Send test data to the remote device.
Send(client, message);
sendDone.WaitOne();
// Receive the response from the remote device.
if (expectResponse)
{
Receive(client);
receiveDone.WaitOne();
}
// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Close();
return response;
}
catch (Exception e)
{
Log.Write(e, false);
return "";
}
}
private static void Send(Socket client, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
Log.WriteSingleMessage(String.Format("Sent {0} bytes to server.", bytesSent), false);
// Signal that all bytes have been sent.
sendDone.Set();
}
catch (Exception e)
{
Log.Write(e, false);
}
}
}
The client code is triggered by a button click event. The problem that I'm facing is that the server code above only works once. If I send a message to the server with the client code, the server processes the string perfect. However, if I hit the button a second time, the SocketListener_ConnectionReceived event is triggered but no data is coming in. I've tried several classes for ConnectionReceived but they all behave the same.
I checked with netstat on the Raspberry Pi if the server is listening and it is.
TCP 0.0.0.0:8888 0.0.0.0:0 LISTENING
Even child processes are created for handling the connection as you would expect from an Async calls. The client code closes the socket after it received a message that the data has been send (waitOne()) and the socket on the client machines changes to CLOSE_WAIT.
TCP 10.0.102.10:8888 10.0.100.11:31298 CLOSE_WAIT
TCP 10.0.102.10:8888 10.0.100.11:31299 ESTABLISHED
Can anyone help me out and point me in the right direction as to what I'm doing wrong. any help would be highly appreciated.
You can try to use synchronous methods instead asynchronous methods for socket client. It will work. Please refer to following code:
public void SendMessageToClientSync(string ip, int port, string message, bool expectResponse)
{
// 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.
IPAddress ipAddress = IPAddress.Parse(ip);
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
Socket sender = new Socket(ipAddress.AddressFamily,
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(message);
// Send the data through the socket.
int bytesSent = sender.Send(msg);
if(expectResponse)
{
// 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());
}
}
I'm going to create a socket to send a string from console application server to AndroidWearable client. I use Visual Studio Xamarin, and I never use XML Language. When I click the button nothing happens, How can I improve my program?
Part MainActivity.cs
using Android.App;
using Android.OS;
using Android.Support.Wearable.Activity;
using Android.Views;
using Android.Widget;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace AndroidClient
{
[Activity(Label = "#string/app_name", MainLauncher = true)]
public class MainActivity : WearableActivity
{
private TextView textView;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.activity_main);
textView = FindViewById<TextView>(Resource.Id.text);
SetAmbientEnabled();
}
/** Called when the user touches the button */
// Incoming data from the client.
public static string data = null;
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
data = null;
// An incoming connection needs to be processed.
while (true)
{
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public void mainsendMessage(View view)
{
// Do something in response to button click
StartListening();
}
}
}
Part AXML-Origin
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage" />
Server C#
SERVER
using System;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Server_microsoft
{
public class SynchronousSocketListener
{
// Incoming data from the client.
public static string data = null;
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(ipAddress.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
data = null;
// An incoming connection needs to be processed.
while (true)
{
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf(data) > -1)
{
break;
}
}
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static int Main(String[] args)
{
StartListening();
return 0;
}
}
}
Thanks!
For example I have to inser some TextView o see the string? How can I make this or one button is necessary?
I have been troubleshooting an issue that I encountered when using a library called AMQP .Net Lite (https://github.com/Azure/amqpnetlite) and have determined that it can be reproduced using a simple .NET Sockets client and server. My repro environment uses a client that sends simple text messages to the server based on some Microsoft samples (see below).
I have noticed after I sign into my company VPN that messages fail to transfer with the following error:
SocketException : System.Net.Sockets.SocketException (0x80004005): An existing connection was forcibly closed by the remote host
I am running both client and server locally on my machine when I encounter the issue.
I have read about this exception and learned that one cause is that the network link has gone down for some reason. This makes sense as logging into VPN must temporarily break the connection, thereby causing the exception. However, one interesting observation is that this problem only occurs when the server is hosting using IPv6. If I force it to use IPv4, then there is no loss of connectivity. Is there a simple explanation for that?
I am also wondering if there is some way to detect that the Socket is in a bad state without sending data? Are there some properties on the Socket I can inspect such that I can detect an issue and force a reconnect? If not, what do people typically do in this situation to ensure the failed messages are accounted for after reconnection?
Interestingly, with my test client, I have to send 2 messages before the exception is thrown, but neither message is received by the server (see picture below).
I am not a networking expert so bear with me if this is fundamental stuff.
Here is my client:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
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.GetHostEntry(Environment.MachineName);
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket sender = new Socket(AddressFamily.InterNetworkV6,
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");
Console.WriteLine("Press any key to send a message...");
int i = 0;
while (true)
{
Console.ReadLine();
// Send the data through the socket.
int bytesSent = sender.Send(msg);
Console.WriteLine(++i + " messages sent");
}
// 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());
}
Console.ReadLine();
}
public static int Main(String[] args)
{
StartClient();
return 0;
}
}
Here is my server:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SynchronousSocketListener
{
// Incoming data from the client.
public static string data = null;
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.IPv6Any, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetworkV6,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Program is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
// An incoming connection needs to be processed.
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data = Encoding.ASCII.GetString(bytes, 0, bytesRec);
Console.WriteLine(data);
}
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
byte[] msg = Encoding.ASCII.GetBytes(data);
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static int Main(String[] args)
{
StartListening();
return 0;
}
}
Here is a screenshot of the problem:
I'm using .NET synchronous socket to send data from a client to server.
I need to get the data from the StartListening() method to use it in the Main() but
the variable data is inside an infinite loop ( while(true)).
Any help please?
This is the server code :
using System;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class SynchronousSocketListener
{
byte[] bytes = new Byte[1024];
IPHostEntry ipHostInfo;
IPAddress ipAddress ;
IPEndPoint localEndPoint;
Socket listener;
// Incoming data from the client.
public static string data = null;
// Volatile is used as hint to the compiler that this data
// member will be accessed by multiple threads.
private volatile bool _shouldStop;
public void InitializeListening()
{
// Data buffer for incoming data.
// Establish the local endpoint for the socket.
// Dns.GetHostName returns the name of the
// host running the application.
ipHostInfo = Dns.Resolve("localhost");
ipAddress = ipHostInfo.AddressList[0];
localEndPoint = new IPEndPoint(ipAddress, 11007);
// Create a TCP/IP socket.
listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(localEndPoint);
listener.Listen(10);
}
public void StopListening()
{
_shouldStop = true;
byte[] msg = Encoding.ASCII.GetBytes("please stop!");
// 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(localEndPoint);
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// 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());
}
}
public void StartListening()
{
// Bind the socket to the local endpoint and
// listen for incoming connections.
try
{
// Start listening for connections.
while (true)
{
Console.WriteLine("Waiting for a connection...");
// Thread is suspended while waiting for an incoming connection.
Socket handler = listener.Accept();
// An incoming connection needs to be processed.
if (_shouldStop)
{
handler.Shutdown(SocketShutdown.Both);
handler.Close();
break;
}
data = null;
while (true)
{
bytes = new byte[1024];
int bytesRec = handler.Receive(bytes);
data += Encoding.ASCII.GetString(bytes, 0, bytesRec);
if (data.IndexOf("<EOF>") > -1)
{
break;
}
}
// Show the data on the console.
Console.WriteLine("Text received : {0}", data);
// Echo the data back to the client.
//byte[] msg = Encoding.ASCII.GetBytes(data);
byte[] msg = Encoding.ASCII.GetBytes("Salam !");
handler.Send(msg);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args)
{
Console.WriteLine("I am the Synchronous Socket Server\n");
SynchronousSocketListener pServer = new SynchronousSocketListener();
pServer.InitializeListening();
Thread serverkerThread = new Thread(pServer.StartListening);
serverkerThread.Start();
// Loop until server thread activates.
while (!serverkerThread.IsAlive) ;
Console.WriteLine("listening thread sevice started...\n");
Console.WriteLine("\nPress Q when you want to quit...\n");
int car;
do
{
Thread.Sleep(100);
car = Console.Read();
if (car == 81)
{
// Request that the worker thread stop itself:
pServer.StopListening();
// Use the Join method to block the current process
// until the object's thread terminates.
serverkerThread.Join();
break;
}
} while (true);
Console.WriteLine("listening thread sevice stopped and program will be exited...\n");
return 0;
}
}
The received data (given it is an ASCII-string ending with "EOF") is stored in the public member named "data" of your pServer object, you can access it like this:
Thread serverkerThread = new Thread(pServer.StartListening);
serverkerThread.Start();
// Loop until server thread activates.
while (!serverkerThread.IsAlive) ;
string receivedString = pServer.data; // <<--- here we get the received string
Console.WriteLine("listening thread sevice started...\n");