public static byte[] StartClient(string ip, int port, byte[] message, bool needBack, out string errorMsg)
{
// Data buffer for incoming data.
byte[] bytes = new byte[1024];
// 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.
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect the socket to the remote endpoint. Catch any errors.
try
{
sender.Connect(remoteEP);
// Send the data through the socket.
int bytesSent = sender.Send(message);
if (needBack)
{
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
byte[] array = new byte[bytesRec];
Array.Copy(bytes, array, bytesRec);
sender.Shutdown(SocketShutdown.Both);
sender.Close();
errorMsg = "";
return array;
}
else
{
errorMsg = "";
return null;
}
}
catch (ArgumentNullException ane)
{
errorMsg = string.Format("ArgumentNullException : {0}", ane.ToString());
return null;
}
catch (SocketException se)
{
errorMsg = string.Format("SocketException : {0}", se.ToString());
return null;
}
catch (Exception e)
{
errorMsg = string.Format("Unexpected exception : {0}", e.ToString());
return null;
}
}
catch (Exception e)
{
errorMsg = string.Format("Unexpected exception : {0}", e.ToString());
return null;
}
}
I use the code above to send and receive tcp message from the server.but I read nothing.
I don't want a async method.I have searched some example codes, they are written like this. Is there something wrong that I didn't realized.Thanks for help.
public class MyTcpClient
{
IPEndPoint _remote;
Socket _socket;
public bool IsStopReceive{set;get;}
public MyTcpClient(string ip, int port)
{
IPAddress ipAddress = IPAddress.Parse(ip);
_remote = new IPEndPoint(ipAddress, port);
_socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
_socket.Connect(_remote);
ThreadPool.QueueUserWorkItem(obj=>{
IsStopReceive = false;
ReceiveMsg();
});
}
public void Send(byte[] bytes) {
_socket.Send(bytes);
}
private MemoryStream memoryResult;
private void ReceiveMsg()
{
MemoryStream memStream = new MemoryStream();
while (!IsStopReceive)
{
byte[] bytes=new byte[1024];
int result = _socket.Receive(bytes);
if (result > 0) {
memStream.Write(bytes, 0, result);
}
else if (result == 0) {
IsStopReceive = true;
break;
}
}
if (OnMsgReceive != null) {
OnMsgReceive(memStream.GetBuffer());
}
}
public Action<byte[]> OnMsgReceive{set;get;}
}
the code above can receive the data.when I create a MyTcpClient instance,it will open a thread to receive data after connect to the target.
I use a Action to get the data after it finished.but this is async.Most important is that I don't know why I missed the data with the prev method.
Related
I have a server in C that send message to unity. In Unity, I can receive data once, but when the server sends a new message, unity receives nothing.
For example: Unity can connect to server, receive the first message that said "move right" and move the camera of Unity to the right but then if the server send "move left" or anything else unity is block in the function receive which calls BeginReceive:
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
Code of my server:
void connectToUnity() {
SOCKADDR_IN sin;
WSAStartup(MAKEWORD(2, 0), &WSAData);
sock = socket(AF_INET, SOCK_STREAM, 0);
sin.sin_addr.s_addr = inet_addr("127.0.0.1");
sin.sin_family = AF_INET;
sin.sin_port = htons(53660);
bind(sock, (SOCKADDR*)&sin, sizeof(sin));
listen(sock, 0);
printf("Connexion to unity\n");
}
void sendDataToUnity(const char * mouvement) {
SOCKET csock;
while (1)
{
int sinsize = sizeof(csin);
if ((csock = accept(sock, (SOCKADDR*)&csin, &sinsize)) != INVALID_SOCKET)
{
send(csock, mouvement, 14, 0);
printf("Donnees envoyees \n");
return;
}
else {
printf("Rien n'a ete envoye");
}
}
}
Code in Unity:
public bool ConnectToServer(string hostAdd, int port)
{
//connect the socket to the server
try
{
//create end point to connect
conn = new IPEndPoint(IPAddress.Parse(hostAdd), port);
//connect to server
clientSocket.BeginConnect(conn, new AsyncCallback(ConnectCallback), clientSocket);
socketReady = true;
connectDone.WaitOne();
Debug.Log("Client socket ready: " + socketReady);
// Receive the response from the remote device.
Receive(clientSocket);
//receiveDone.WaitOne();
}
catch (Exception ex)
{
Debug.Log("socket error: " + ex.Message);
}
return socketReady;
}
//async call to connect
static void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket
Socket client = (Socket)ar.AsyncState;
// Complete the connection
client.EndConnect(ar);
Debug.Log("Client Socket connected to: " + client.RemoteEndPoint);
connectDone.Set();
}
catch (Exception e)
{
Debug.Log("Error connecting: " + e);
}
}
private static void Receive(Socket client)
{
try
{
Debug.Log("Try to receive");
// Create the state object.
StateObject state = new StateObject();
state.workSocket = client;
// Begin receiving the data from the remote device.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
Debug.Log(e);
}
}
static void ReceiveCallback(IAsyncResult ar)
{
try
{
//Read data from the remote device.
Debug.Log("receive callback");
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
Debug.Log("Il y a une réponse");
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReceiveCallback), state);
response = state.sb.ToString();
Debug.Log(response);
//client.Shutdown(SocketShutdown.Both);
}
else
{
if(state.sb.Length > 1)
{
response = state.sb.ToString();
Debug.Log(response);
}
}
}
catch (Exception ex)
{
Debug.Log("Error: " + ex.Message);
}
}
The function receive is called once in the function ConnectToServer, then I tried to call again in the update like this:
void Update()
{
if (response.Contains("right"))
{
Debug.Log("Move to the right ");
float x = Camera.main.transform.localEulerAngles.x;
float y = Camera.main.transform.localEulerAngles.y;
DeplacementCamera.moveRight(x, y);
response = "";
Receive(clientSocket);
}
}
I have already see this post but without success or maybe I tried it in the wrong way:
Why does BeginReceive() not return for more than one read?
Edit: In the function ReceiveCallback the else is never reached.
you may change your method
private void SetupReceiveCallback(Socket sock)
{
try
{
DataBuffer = new byte[BufferSize];
AsyncCallback recieveData = new AsyncCallback(OnRecievedData);
sock.BeginReceive(DataBuffer, 0, DataBuffer.Length, SocketFlags.None, recieveData, _socket);
}
catch (Exception E)
{
}
}
private void OnRecievedData(IAsyncResult ar)
{
Socket sock = (Socket)ar.AsyncState;
try
{
if (sock.Connected)
{
int nBytesRec = sock.EndReceive(ar);
if (nBytesRec > 0)
{
string Data = Encoding.UTF8.GetString(DataBuffer);
if (Data.Length != 4)
{
string JsonString = Data;
if (!string.IsNullOrEmpty(JsonString))
{
try
{
//Add you code processing here
}
catch (Exception ex)
{
}
}
BufferSize = 4;
}
else
{
BufferSize = BitConverter.ToInt32(DataBuffer, 0);
}
}
SetupReceiveCallback(sock);
}
else
// on not connected to socket
}
catch (Exception E)
{
}
}
public bool Connect(string IP, int Port)
{
try
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//if (IsValidIP(IP))
//{
// IPEndPoint epServer = new IPEndPoint(IPAddress.Parse(IP), Port);
// _socket.Connect(epServer);
//}
//else
//{
// _socket.Connect(IP, Port);
//}
//SetupReceiveCallback(_socket);
}
catch(Exception ex)
{
}
return false;
}
I'm using c# sockets to create a client-server connection on my pc, for now locally, but the exception in the title is the only signal I receive back.
I've already tried disabling the firewall, checking if the port I'm using(51111) is listening(yes) and unticking everything in LAN settings(to avoid proxying), all of them at the same time too.
My code(just temporary test code)
Server Class
class Server
{
private Socket listener;
public void SocketServer()
{
int maxBuffer = 1024;
Console.WriteLine("LISTENER ENABLED");
listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(new IPEndPoint(IPAddress.Any, 51111));
listener.Listen(5);
while (true)
{
Console.WriteLine("WAITING FOR CONNECTION");
Socket socket = listener.Accept();
string receivedMessage = string.Empty;
while (true)
{
byte[] receivedBytes = new byte[maxBuffer];
int bytesReceivedCount = socket.Receive(receivedBytes);
receivedMessage += Encoding.ASCII.GetString(receivedBytes, 0, bytesReceivedCount);
if (receivedMessage.IndexOf('\n') > -1)
{
break;
}
}
Console.WriteLine("Message from Client : " + receivedMessage);
string reply = ("Message received!");
byte[] replyBytes = Encoding.ASCII.GetBytes(reply);
socket.Send(replyBytes);
socket.Shutdown(SocketShutdown.Both);
socket.Close();
}
}
Client Class
class Client
{
public void SocketClient(string request)
{
int maxBuffer = 1024;
try
{
IPHostEntry iPHostEntry = Dns.GetHostEntry(Dns.GetHostName());
IPAddress address = iPHostEntry.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(address, 51111);
Socket sender = new Socket(address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
sender.Connect(remoteEP);
Console.WriteLine("Connected to " + sender.RemoteEndPoint.ToString());
byte[] message = Encoding.ASCII.GetBytes(request);
int bytesSent = sender.Send(message);
byte[] response = new byte[maxBuffer];
int bytesReceived = sender.Receive(response);
Console.WriteLine("Received : " + Encoding.ASCII.GetString(response, 0, bytesReceived));
}
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());
}
}
}
Thank you
I have a console application which acts as a socket server. It should accept data 24/7 from a number of clients, but issue is that the clients cannot establish connection after sometime (not constant). after closing & opening the connection works & it continues to next point of time.
Server
public static void ExecuteServer()
{
int portNumber = 11111;
string _responseMessageToClient = "";
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, portNumber);
// Creation TCP/IP Socket using
// Socket Class Costructor
Socket listener = new Socket(ipAddr.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
bool doBroadCast = false;
try
{
listener.Bind(localEndPoint);
listener.Listen(10);
while (true)
{
try`enter code here`
{
Socket clientSocket = listener.Accept();
// Data buffer
byte[] bytes = new Byte[1024*2];//2048
string data = null;
while (true)
{
try
{
if (clientSocket.Connected)
{
int numByte = clientSocket.Receive(bytes);
data += Encoding.ASCII.GetString(bytes,
0, numByte);
if (data.IndexOf("!") > -1)
break;
}
else
{
Console.WriteLine("Disconnected {0}", clientSocket.LocalEndPoint);
break;
}
}
catch (Exception e)
{
//ErrorLogProvider.Save(e);
Console.WriteLine(e.ToString());
break;
}
}
Console.WriteLine("Text received -> {0} ", data);
if (clientSocket.Connected)
{
clientSocket.Send(message);
}
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
catch (Exception e)
{
}
}
}
catch (Exception e)
{
}
}
This server has to be running continuously - Client code given below
static void ExecuteClient()
{
try
{
// Establish the remote endpoint
// for the socket. This example
// uses port 11111 on the local
// computer.
int portNumber = 11111;
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, portNumber);
// Creation TCP/IP Socket using
// Socket Class Costructor
Socket sender = new Socket(ipAddr.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
long i = 0;
try
{
//while (i < 10)
//{
// Connect Socket to the remote
// endpoint using method Connect()
sender.Connect(localEndPoint);
// We print EndPoint information
// that we are connected
Console.WriteLine("Socket connected to -> {0} ",
sender.RemoteEndPoint.ToString());
// Creation of messagge that
// we will send to Server
byte[] messageSent = Encoding.ASCII.GetBytes("^check!");
int byteSent = sender.Send(messageSent);
// Data buffer
byte[] messageReceived = new byte[1024];
// We receive the messagge using
// the method Receive(). This
// method returns number of bytes
// received, that we'll use to
// convert them to string
int byteRecv = sender.Receive(messageReceived);
Console.WriteLine("Message from Server -> {0}",
Encoding.ASCII.GetString(messageReceived,
0, byteRecv));
//}
// Close Socket using
// the method Close()
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
// Manage of Socket's Exceptions
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've got this code somewhere from SO if I remember that correctly.
LoopClients just checks for new clients and handles them by spawning a new thread.
class Server {
private TcpListener _server;
private Boolean _isRunning = true;
private int m_Port = 12001;
private Thread m_ServerThread;
public Server (int p_Port) {
_server = new TcpListener(IPAddress.Any, m_Port);
_server.Start( );
m_ServerThread = new Thread(new ThreadStart(LoopClients));
m_ServerThread.Start( );
}
public void ShutdownServer() {
_isRunning = false;
}
public void LoopClients ( ) {
while ( _isRunning ) {
// wait for client connection
TcpClient newClient = _server.AcceptTcpClient( );
// client found.
// create a thread to handle communication
Thread t = new Thread(new ParameterizedThreadStart(HandleClient));
t.Start(newClient);
}
}
public void HandleClient (object obj) {
try {
// retrieve client from parameter passed to thread
TcpClient client = (TcpClient) obj;
// sets two streams
StreamWriter sWriter = new StreamWriter(client.GetStream( ), Encoding.ASCII);
StreamReader sReader = new StreamReader(client.GetStream( ), Encoding.ASCII);
// you could use the NetworkStream to read and write,
// but there is no forcing flush, even when requested
String sData = null;
while ( client.Connected ) {
sData = sReader.ReadToEnd( );
if ( sData != "" )
break;
}
try {
sWriter.WriteLine("test");
} catch(Exception ex) {
Console.WriteLine(ex.Message);
}
sWriter.Dispose( );
sReader.Dispose( );
sWriter = null;
sReader = null;
} catch ( IOException ioe ) {
}
}
}
Client is somewhat shorter. I've got to shorten the code a bit here.
Client:
private void sendDataViaTCP () {
TcpClient l_Client = new TcpClient();
l_Client.Connect(IP, Port);
Stream l_Stream = l_Client.GetStream( );
StreamWriter l_SW = new StreamWriter(l_Stream);
StreamReader l_SR = new StreamReader(l_SW.BaseStream);
try {
l_SW.WriteLine(Msg);
l_SW.Flush( );
String l_IncomingData;
while ( ( l_IncomingData = l_SR.ReadToEnd()) != "") {
AddLineToLog(l_IncomingData);
}
} finally {
l_SW.Close( );
}
}
i've got the following problem in a client socket (sync) / server socket (async) environment.
If I send multiple messages from the client to the server, the first one finishs without any problems and will be received by the client without issues. When I send the 2nd message, just a few bytes go through. It doesn't seem to be a client problem, because it looks the client sends the whole message all the time. The crazy thing is, if I completely stop the project on the client and start again the first message completes again, also if the server component runs through all the time.
What I want to do...
Basically, I want to transfer different objects, most xml structured through the network and receive it on the client. Therefore, I do the Serialization/Deserialization.
The basics of the following code are extended msdn examples.
//CLIENT:
class ProgramClient
{
static void Main(string[] args)
{
string rootNode = "config";
StreamReader configStream = new StreamReader(config);
XmlDocument xml = new XmlDocument();
xml.Load(configStream);
SynchronousSocketClient socket = new SynchronousSocketClient("192.168.0.1", 40001, "c:\\log", xml);
socket.StartClient();
socket.Dispose();
socket = new SynchronousSocketClient("192.168.0.1", 40001, "c:\\log", xml);
socket.StartClient();
socket.Dispose();
}
}
class SynchronousSocketClient : IDisposable
{
private string ip;
private int port;
private object data;
public StreamWriter log;
public event EventHandler Disposed;
public SynchronousSocketClient(string ip, int port, string logfile, object data)
{
this.ip = ip;
this.port = port;
this.data = data;
openLog(logfile);
}
public void openLog(string logfile)
{
log = new StreamWriter(logfile, true);
}
public void Dispose()
{
log.Close();
if (this.Disposed != null)
this.Disposed(this, EventArgs.Empty);
}
// Convert an object to a byte array
private byte[] Serialize(object obj)
{
Stream stream = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(stream, obj);
byte[] b = null;
b = new byte[stream.Length];
stream.Position = 0;
stream.Read(b, 0, (int)stream.Length);
stream.Close();
return b;
}
public 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(ip);
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress,port);
// 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);
log.WriteLine(DateTime.Now+": Socket connected to {0}",
sender.RemoteEndPoint.ToString());
// Encode the data string into a byte array.
byte[] msg = Serialize(data);
// Send the data through the socket.
int bytesSent = sender.Send(msg);
// Receive the response from the remote device.
int bytesRec = sender.Receive(bytes);
log.WriteLine(DateTime.Now + ": {0}",
Encoding.Unicode.GetString(bytes,0,bytesRec));
// Release the socket.
sender.Shutdown(SocketShutdown.Both);
sender.Close();
} catch (ArgumentNullException ane) {
log.WriteLine(DateTime.Now + ": ArgumentNullException : {0}", ane.ToString());
} catch (SocketException se) {
log.WriteLine(DateTime.Now + ": SocketException : {0}", se.ToString());
} catch (Exception e) {
log.WriteLine(DateTime.Now + ": Unexpected exception : {0}", e.ToString());
}
} catch (Exception e) {
log.WriteLine(DateTime.Now+": "+e.ToString());
}
}
}
//SERVER:
class ProgramServer
{
static void Main(string[] args)
{
NetworkSocket socket = new NetworkSocket(nwsocketport);
socket.Start();
}
}
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of send buffer.
public const int sBufferSize = 1024;
// send buffer.
public byte[] sBuffer = new byte[sBufferSize];
// Received data object;
public object data = null;
// bytes read so far
public int bytesRead;
//receive buffer
public byte[] rBuffer;
}
public class NetworkSocket
{
private int port;
Socket listener;
IPEndPoint localEndPoint;
public NetworkSocket(int port) {
this.port = port;
}
public void Start() {
// Establish the local endpoint for the socket.
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[1];
localEndPoint = new IPEndPoint(ipAddress, port);
// Create a TCP/IP socket.
listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
//set socket timeouts
listener.SendTimeout = 5000;
listener.ReceiveTimeout = 5000;
// Bind the socket to the local endpoint and listen for incoming connections.
try {
listener.Bind(localEndPoint);
listener.Listen(1);
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
public void AcceptCallback(IAsyncResult ar) {
// Signal the main thread to continue.
//allDone.Set();
// Get the socket that handles the client request.
Socket listener = (Socket) ar.AsyncState;
Socket handler = listener.EndAccept(ar);
// Create the state object.
StateObject state = new StateObject();
// Data buffer for incoming data.
state.rBuffer = new Byte[listener.ReceiveBufferSize];
state.workSocket = handler;
handler.BeginReceive(state.rBuffer, 0, state.rBuffer.Length, 0,
new AsyncCallback(ReadCallback), state);
try
{
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public void ReadCallback(IAsyncResult ar) {
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject) ar.AsyncState;
Socket handler = state.workSocket;
//handler.ReceiveTimeout = 2000;
// Read data from the client socket.
state.bytesRead = handler.EndReceive(ar);
Send(handler, "paket successfully tranferred");
state.data = Deserialize(state.rBuffer);
bool xmlDoc = true;
try
{
XDocument.Parse(state.data.ToString());
}
catch
{
xmlDoc = false;
}
if (xmlDoc)
XMLHandler.update(state.data.ToString());
}
private void Send(Socket handler, String data) {
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.Unicode.GetBytes(data);
// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), handler);
}
private void SendCallback(IAsyncResult ar) {
try {
// Retrieve the socket from the state object.
Socket handler = (Socket) ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
// Convert a byte array to an Object
private object Deserialize(byte[] b)
{
MemoryStream stream = new MemoryStream(b);
BinaryFormatter bf = new BinaryFormatter();
object obj = bf.Deserialize(stream);
stream.Close();
return obj;
}
// convert object to byte array
private byte[] Serialize(object obj)
{
Stream stream = new MemoryStream();
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(stream, obj);
byte[] b = null;
b = new byte[stream.Length];
stream.Position = 0;
stream.Read(b, 0, (int)stream.Length);
stream.Close();
return b;
}
}
Could anybody please help me with my problem? I am not experienced in Socket Programming...
In your ReadCallback you need to start another BeginReceive, just like how you call BeginAccept in the AcceptCallback method.
A more serious issue with your code is that you expect to receive one entire message per ReadCallback. In reality, you could receive half a message, one byte, or three messages.
I used to write socket programs in C and can't understand why the above is happening.
My server blocks at a Receive call, when it returns 0, I break out of the while loop and shutdown the thread.
public class MyServer {
public MyServer() {
}
public void Init() {
ThreadPool.QueueUserWorkItem(StartListening);
while (true) {
Console.Read();
}
}
public void StartListening(Object state) {
// Establish the local endpoint for the socket.
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try {
// Bind the socket to the local endpoint and listen for incoming connections.
listener.Bind(localEndPoint);
listener.Listen(100);
while (true) {
Console.WriteLine("Waiting for a connection...");
// get connection
Socket client = listener.Accept();
// push client to another thread
ThreadPool.QueueUserWorkItem(HandleClient, client);
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
}
private void HandleClient(Object obj) {
// Get the socket that handles the client request.
Socket client = (Socket)obj;
// Create the state object.
StateObject state = new StateObject();
state.workSocket = client;
try {
while (true) {
int bytesRead = client.Receive(state.buffer);
Console.WriteLine("bytesRead=" + bytesRead);
// remote dc.
if (bytesRead == 0)
break;
String content = Encoding.ASCII.GetString(state.buffer, 0, bytesRead);
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content);
client.Send(state.buffer, 0, state.buffer.Length, 0);
}
} catch (SocketException e) {
Console.WriteLine("SocketException : {0}", e.ToString());
}
client.Shutdown(SocketShutdown.Both);
client.Close();
}
private void Send(Socket handler, String data) {
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
//handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
}
}
However, when I click on the close button ("x") of the client, server's Receive call throws a SocketException. According to MSDN's Remarks section, this shouldn't happen because I've satisfied both the connection-oriented part (see above) and client shutdown part(see below) conditions.
Client.cs (pseudo):
public class MyClient {
public void Init() {
byte[] bytes = new byte[1024];
Socket sender = null;
try {
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",
sender.RemoteEndPoint.ToString());
while (true) {
// Encode the data string into a byte array.
String input = Console.ReadLine();
byte[] msg = Encoding.ASCII.GetBytes(input);
// 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));
}
} 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());
} finally {
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
}
}
My shallow understanding of finally blocks is that it will always execute. But it doesn't seem to be the case here.
SO, what did I do wrong here? Should I just catch the exception, close the client socket on the server side and just move on, ignoring it? But I would prefer if an exception were not thrown at all.