Handling exceptions in Socket programming - c#

public partial class Form1 : Form
{
private void button1_Click(object sender, EventArgs e)
{
String text = textBox1.Text;
UdpClient udpc = new UdpClient(text,8899);
IPEndPoint ep = null;
while (true)
{
MessageBox.Show("Name: ");
string name = "Connected";
if (name == "") break;
byte[] sdata = Encoding.ASCII.GetBytes(name);
udpc.Send(sdata, sdata.Length);
if (udpc.Receive(ref ep)==null)
{
MessageBox.Show("Host not found");
}
else
{
byte[] rdata = udpc.Receive(ref ep);
string job = Encoding.ASCII.GetString(rdata);
MessageBox.Show(job);
}
}
}
I'm getting an error message when my remote machine is not connected . with this code im getting the errror.
if (udpc.Receive(ref ep)==null)
error message is socket exception was unhanded ( An existing connection was forcibly closed by the remote host)

Wrap the code in a
try
{
}
catch(SocketException se)
{
}
catch(Exception ex)
{
}
And start here for documentation on SocketException
http://msdn.microsoft.com/en-us/library/system.net.sockets.socketexception.aspx

If the exception is unhandled, so handle the exception:
while (true)
{
MessageBox.Show("Name: ");
string name = "Connected";
if (name == "") break;
byte[] sdata = Encoding.ASCII.GetBytes(name);
try{
udpc.Send(sdata, sdata.Length);
byte[] rdata = udpc.Receive(ref ep);
string job = Encoding.ASCII.GetString(rdata);
MessageBox.Show(job);
}
catch(Exception ex)
{
MessaageBox.show(ex.toString());
}
}
The try...catch block is always recommended when the program accesses external resources (dbs, queues, file systems, http connections, udp sockets etc.)

You can wrap your infinite loop in a try catch block.
try
{
while(true)
{
//your code
}
}
catch(Exception exception)
{
//show exception.Message;
}
finally{ //clean up}
Look at how it is done.

Related

Error Handling in TcpClient Socket

I am new to Sockets this is my Code to send and receive data from a server.
This Code Works fine as long as the Client is able to receive data from the server.
In Case the Server does not sends the answer back in the given time then the application needs to send "No Answer Received".
How can i know if the recvBuffer is empty or NULL.
Currently the if Condition for the recvBuffer does not work and the application tries to send empty buffer which results in "System.IndexOutOfRangeException error".
class GetSocket
{
public string SocketSendReceive(string server, int port, string cmd)
{
byte[] recvBuffer = new byte[1024];
TcpClient tcpClient = new TcpClient();
tcpClient.Client.ReceiveTimeout = 200;
try
{
tcpClient.Connect(server, 6100);
}
catch (SocketException e)
{
MessageBox.Show(e.Message);
}
if (tcpClient != null && tcpClient.Connected)
{
try
{
tcpClient.Client.Send(Encoding.UTF8.GetBytes(cmd));
tcpClient.Client.Receive(recvBuffer);
}
catch (SocketException e)
{
MessageBox.Show(e.ErrorCode.ToString());
}
tcpClient.GetStream().Close();
tcpClient.Client.Close();
tcpClient.Client.Dispose();
tcpClient = null;
string tmp = Encoding.ASCII.GetString(recvBuffer, 0, recvBuffer.Length);
if (recvBuffer != null && recvBuffer.Length > 0)
{
string[] words = tmp.Split(null);
return words[1];
}
else
{
return ("No Answer Received");
}
}
return null;
}
}
The Following code works fine after making changes as suggested.
class GetSocket
{
public string SocketSendReceive(string server, int port, string cmd)
{
byte[] recvBuffer = new byte[1024];
TcpClient tcpClient = new TcpClient();
tcpClient.Client.ReceiveTimeout = 200;
string tmp;
try
{
tcpClient.Connect(server, 6100);
}
catch (SocketException e)
{
MessageBox.Show(e.Message);
}
if (tcpClient != null && tcpClient.Connected)
{
try
{
tcpClient.Client.Send(Encoding.UTF8.GetBytes(cmd));
tcpClient.Client.Receive(recvBuffer);
tmp = Encoding.ASCII.GetString(recvBuffer, 0, recvBuffer.Length);
string[] words = tmp.Split(null);
return words[1];
}
catch (SocketException e)
{
return ("No Answer Received");
}
}
return null;
}
}

Socket Error 10054 : Error Handling Issue

Eveyone.
How to resolve the Error code 10054 ? There are some description about this error. Here is my full source code for communication. I want to know whether my code is ok or not.
WSAECONNRESET10054 Connection reset by peer. An existing connection
was forcibly closed by the remote host. This normally results if the
peer application on the remote host is suddenly stopped, the host is
rebooted, the host or remote network interface is disabled, or the
remote host uses a hard close (see setsockopt for more information on
the SO_LINGER option on the remote socket). This error may also result
if a connection was broken due to keep-alive activity detecting a
failure while one or more operations are in progress. Operations that
were in progress fail with WSAENETRESET. Subsequent operations fail
with WSAECONNRESET.
Full Source Code
using System;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Threading;
using LogManager;
namespace CoreUnitPlatform
{
public class SocketCommCoreUnit
{
#region property
private volatile bool _shouldStop;
private LogWriter log = LogWriter.Instance;
private bool m_bSocketConnected = false;
private Socket m_clientSocket = null;
private SocketCommType m_connectedSockType;
private EventHandlerDataReceived m_evtHandlerDataReceived;
private EventHandlerSocketConnected m_evtHandlerSocketConnected;
private EventHandlerSocketConnectedFailed m_evtHandlerSocketConnectedFailed;
private EventHandlerSocketDisconnected m_evtHandlerSocketDisconnected;
private IPAddress m_IPAddress;
private IPEndPoint m_IPEndPoint;
private int m_portNo;
private Socket m_serverSocket = null;
private Thread m_threadConnectSocket = null;
private string Name = string.Empty;
#endregion
#region constructor
public SocketCommCoreUnit()
{
this.Name = "SocketCommCoreUnit";
Instance();
}
#endregion
#region delegatge
public delegate void EventHandlerDataReceived(string msg);
public delegate void EventHandlerSocketConnected();
public delegate void EventHandlerSocketConnectedFailed();
public delegate void EventHandlerSocketDisconnected();
public enum SocketCommType { SERVER, CLIENT };
public bool SocketConnected
{
get { lock (this) { return m_bSocketConnected; } }
set { lock (this) { m_bSocketConnected = value; } }
}
#endregion
#region public
public void ConnectSocketProc()
{
while (!_shouldStop)
{
try
{
if (SocketConnected == false)
{
if (m_connectedSockType == SocketCommType.SERVER)
{
m_clientSocket = m_serverSocket.Accept(); // If a client is connected, wait for data from client
m_evtHandlerSocketConnected();
SocketConnected = true;
}
else
{
m_clientSocket.Connect(m_IPAddress, m_portNo);
if (m_clientSocket.Connected == true)
{
m_evtHandlerSocketConnected();
SocketConnected = true;
}
}
}
else
{
try
{
byte[] buffer = new byte[1024];
int readBytes = this.m_clientSocket.Receive(buffer);
if (readBytes == 0)
{
this.reConnect();
}
else
{
string received = System.Text.Encoding.ASCII.GetString(buffer);
m_evtHandlerDataReceived(received);
}
}
catch (SocketException sex)
{
if (sex.NativeErrorCode.Equals(10054))
{
log.AddErrorLog(this.Name, MethodBase.GetCurrentMethod().Name, string.Format("Error Occured [{0}]: MESASGE[{1}]\r\nSOURCE[{2}]\r\nTRACE[{3}]", sex.NativeErrorCode, sex.Message, sex.Source, sex.StackTrace));
this.reConnect();
}
}
}
}
catch
{
m_evtHandlerSocketConnectedFailed();
}
Thread.Sleep(100);
}
}
public void Initialize(string IP, int port, SocketCommType sockType, EventHandlerDataReceived evtHandlerDataReceived, EventHandlerSocketConnected evtHandlerDataConnected, EventHandlerSocketDisconnected evtHandlerSocketDisconnected, EventHandlerSocketConnectedFailed evtHandlerSocketConnectedFailed)
{
m_connectedSockType = sockType;
m_evtHandlerDataReceived = evtHandlerDataReceived;
m_evtHandlerSocketDisconnected = evtHandlerSocketDisconnected;
m_evtHandlerSocketConnected = evtHandlerDataConnected;
m_evtHandlerSocketConnectedFailed = evtHandlerSocketConnectedFailed;
m_portNo = port;
m_IPAddress = IPAddress.Parse(IP);
m_IPEndPoint = new IPEndPoint(m_IPAddress, m_portNo);
if (sockType == SocketCommType.SERVER)
{
OpenServer();
}
else
{
OpenClient();
}
}
public void Instance()
{
}
public void OpenClient()
{
try
{
#if _NO_USE_SOCKET
#else
RunClientSocket();
#endif
}
catch (System.Exception ex)
{
log.AddErrorLog(this.Name, MethodBase.GetCurrentMethod().Name, string.Format("Error Occured: MESASGE[{0}]\r\nSOURCE[{1}]\r\nTRACE[{2}]", ex.Message, ex.Source, ex.StackTrace));
}
}
public void OpenServer()
{
try
{
#if _NO_USE_SOCKET
#else
RunServerSocket();
#endif
}
catch (System.Exception ex)
{
log.AddErrorLog(this.Name, MethodBase.GetCurrentMethod().Name, string.Format("Error Occured: MESASGE[{0}]\r\nSOURCE[{1}]\r\nTRACE[{2}]", ex.Message, ex.Source, ex.StackTrace));
}
}
public void Release()
{
try
{
if (this.m_clientSocket != null && this.m_clientSocket.Connected)
{
SocketConnected = false;
m_evtHandlerSocketDisconnected();
this.m_clientSocket.Shutdown(SocketShutdown.Both);
this.m_clientSocket.Close();
}
if (m_serverSocket != null)
{
m_serverSocket.Close();
}
if ((m_threadConnectSocket != null) && (m_threadConnectSocket.IsAlive == true))
{
Thread.Sleep(1);
RequestStop();
SocketConnected = false;
m_threadConnectSocket.Abort();
m_threadConnectSocket.Join();
}
}
catch (System.Exception ex)
{
log.AddErrorLog(this.Name, MethodBase.GetCurrentMethod().Name, string.Format("Error Occured: MESASGE[{0}]\r\nSOURCE[{1}]\r\nTRACE[{2}]", ex.Message, ex.Source, ex.StackTrace));
}
}
public void RequestStop()
{
_shouldStop = true;
}
public void RunClientSocket()
{
m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
ConfigureTcpSocket(m_clientSocket, SocketCommType.CLIENT);
m_threadConnectSocket = new Thread(new ThreadStart(ConnectSocketProc));
m_threadConnectSocket.Start();
}
public void RunServerSocket()
{
m_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
m_serverSocket.Bind(m_IPEndPoint);
m_serverSocket.Blocking = true; // The server socket is working in blocking mode
ConfigureTcpSocket(m_serverSocket, SocketCommType.SERVER);
m_serverSocket.Listen(1);
m_threadConnectSocket = new Thread(new ThreadStart(ConnectSocketProc));
m_threadConnectSocket.Start();
}
public void Send(byte[] msg)
{
#if _NO_USE_SOCKET
#else
if (SocketConnected == false)
{
throw new Exception("SOCKET_NOT_CONNECT_BEFORE_SEND_DATA;");
}
try
{
m_clientSocket.Send(msg);
}
catch (System.Exception ex)
{
SocketConnected = false;
m_evtHandlerSocketDisconnected();
log.AddErrorLog(this.Name, MethodBase.GetCurrentMethod().Name, string.Format("Error Occured: MESASGE[{0}]\r\nSOURCE[{1}]\r\nTRACE[{2}]", ex.Message, ex.Source, ex.StackTrace));
}
#endif
}
#endregion
#region private
private void ConfigureTcpSocket(Socket tcpSocket, SocketCommType socketCommType)
{
//// Don't allow another socket to bind to this port.
//tcpSocket.ExclusiveAddressUse = true;
//// The socket will linger for 10 seconds after
//// Socket.Close is called.
//tcpSocket.LingerState = new LingerOption(true, 10);
// Disable the Nagle Algorithm for this tcp socket.
tcpSocket.NoDelay = true;
//if (socketCommType == SocketCommType.CLIENT)
//{
// tcpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, false);
// tcpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
// //tcpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 3000);
// //tcpSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 3000);
// // Set the receive buffer size to 8k
// tcpSocket.ReceiveBufferSize = 2048;
// // Set the send buffer size to 8k.
// tcpSocket.SendBufferSize = 2048;
//}
//// Set the receive buffer size to 8k
//tcpSocket.ReceiveBufferSize = 1024;
// Set the timeout for synchronous receive methods to
// 1 second (1000 milliseconds.)
//tcpSocket.ReceiveTimeout = 1000;
//// Set the send buffer size to 8k.
//tcpSocket.SendBufferSize = 1024;
// Set the timeout for synchronous send methods
// to 1 second (1000 milliseconds.)
//tcpSocket.SendTimeout = 1000;
//// Set the Time To Live (TTL) to 42 router hops.
//tcpSocket.Ttl = 42;
}
private void ConfigureTcpSocket(Socket tcpSocket)
{
//// Don't allow another socket to bind to this port.
//tcpSocket.ExclusiveAddressUse = true;
//// The socket will linger for 10 seconds after
//// Socket.Close is called.
//tcpSocket.LingerState = new LingerOption(true, 10);
// Disable the Nagle Algorithm for this tcp socket.
tcpSocket.NoDelay = true;
//// Set the receive buffer size to 8k
//tcpSocket.ReceiveBufferSize = 8192;
// Set the timeout for synchronous receive methods to
// 1 second (1000 milliseconds.)
//tcpSocket.ReceiveTimeout = 1000;
//// Set the send buffer size to 8k.
//tcpSocket.SendBufferSize = 8192;
// Set the timeout for synchronous send methods
// to 1 second (1000 milliseconds.)
//tcpSocket.SendTimeout = 1000;
//// Set the Time To Live (TTL) to 42 router hops.
//tcpSocket.Ttl = 42;
}
private void reConnect()
{
try
{
SocketConnected = false;
m_evtHandlerSocketDisconnected();
m_clientSocket.Disconnect(true);
log.AddSystemLog(this.Name, MethodBase.GetCurrentMethod().Name, string.Format("Try Re-Connection..."));
if (m_connectedSockType == SocketCommType.SERVER)
{
}
else
{
m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
}
catch (System.Exception exc)
{
log.AddErrorLog(this.Name, MethodBase.GetCurrentMethod().Name, string.Format("Error Occured: MESASGE[{0}]\r\nSOURCE[{1}]\r\nTRACE[{2}]", exc.Message, exc.Source, exc.StackTrace));
}
}
#endregion
}
}
I made a (IMOHO) nice post about async sockets here, It has some pseudo code about server/client sockets.
Article: Unable to read data correctly from .Net socket in C#
I think the code of Asynchronous example is great.

How to handle client disconnect in Socket Programming?

I have written a server side code using Sockets, Its working fine but have one problem I don't know how to handle this scenario: if client just closes application without sending Disconnect request, my server side program crashes. What do I need to do to avoid this? Please guide me I am new to Socket programming.
private void OnReceive(IAsyncResult result)
{
try
{
Socket clientSocket = (Socket)result.AsyncState;
clientSocket.EndReceive(result);
command = responseMessage = string.Empty;
command = ByteToString(receviedData);
receviedData = new byte[30];
if (command=="Connect")
{
ClientInfo clientInfo = new ClientInfo();
clientInfo.socket = clientSocket;
clientInfo.IP = clientSocket.RemoteEndPoint.ToString();
connectedClients.Add(clientInfo);
responseMessage = "Connection established...";
}
else if (command=="Disconnect")
{
for (int i = 0; i < connectedClients.Count; i++)
{
if (connectedClients[i].socket == clientSocket)
{
connectedClients.RemoveAt(i);
break;
}
}
clientSocket.Close();
}
else
{
responseMessage = "Error";
}
byte[] responseStatus = StringToByte(responseMessage);
for (int i = 0; i < connectedClients.Count; i++)
{
if (connectedClients[i].socket==clientSocket)
{
connectedClients[i].socket.BeginSend(responseStatus, 0, responseStatus.Length,SocketFlags.None, new AsyncCallback(OnSend), connectedClients[i].socket);
break;
}
}
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
}
Your application crashes, because you throw an exception in the catch block of your method.
If you don't want your application to crash, you need to remove the throw new Exception(ex.Message); line from the catch block.
Replace it with code that handles the error and gracefully restores your application to a safe state. From reading your code, this should be done by removing the clientSocket from connectedClients
Secondly, it is better to just use throw; instead of throw new Exception(ex.Message);. throw; will re-throw the original exception object and thus preserve the stack trace and other vital information that helps in debugging your software.
Using new Exception("Message") will create a completely new exception object with the current stack trace.
private void OnReceive(IAsyncResult result)
{
try
{
Socket clientSocket = (Socket)result.AsyncState;
clientSocket.EndReceive(result);
command = responseMessage = string.Empty;
command = ByteToString(receviedData);
receviedData = new byte[30];
if (command=="Connect")
{
ClientInfo clientInfo = new ClientInfo() {
socket = clientSocket,
IP = clientSocket.RemoteEndPoint.ToString(),
};
connectedClients.Add(clientInfo);
responseMessage = "Connection established...";
}
else if (command=="Disconnect")
{
removeClientInfo(clientSocket);
clientSocket.Close();
}
else
{
responseMessage = "Error";
}
byte[] responseStatus = StringToByte(responseMessage);
for (int i = 0; i < connectedClients.Count; i++)
{
if (connectedClients[i].socket==clientSocket)
{
connectedClients[i].socket.BeginSend(responseStatus, 0, responseStatus.Length,SocketFlags.None, new AsyncCallback(OnSend), connectedClients[i].socket);
break;
}
}
}
catch(Exception ex)
{
// add error handling and gracefully recover
// caution: The way done here, might work, but it smells :-/
removeClientInfo((Socket)result.AsyncState);
((Socket)result.AsyncState).Close();
}
}
/// removes the client info from the connectedClients enumerable
private void removeClientInfo(Socket socket)
{
for (int i = 0; i < connectedClients.Count; i++)
{
if (connectedClients[i].socket == socket)
{
connectedClients.RemoveAt(i);
break;
}
}
}
You are throwing a new exception inside the catch block, which doesn't make much sense unless you're doing some logging or similar. Change the catch block like:
catch(SocketException)
{
}
Also, you should check the number of bytes read returned from EndReceive. If you receive zero bytes, that means the client has shutdown the connection:
int numReceived = clientSocket.EndReceive(result);
if(numReceived == 0)
{
//client has shutdown the connection
}

send data from .Net application to android app via network (socket programming)

I'm new in socket programming. I want to create an application for PC using C# and an application for android phones witch can communicate with other via wireless network(LAN).
For sending data to android app, I'm using this code in PC side:
private void sendButton_Click(object sender, EventArgs e)
{
try
{
Object objData = messageTextBox.Text;
byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString ());
_socket.Send (byData);
}
catch(SocketException se)
{
MessageBox.Show (se.Message );
}
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_ipEndPoint = new IPEndPoint(IPAddress.Parse("192.168.1.18"), 2001);
_socket.Connect(_ipEndPoint);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
In android app, I want to receive data with this code:
Handler myUpdateHandler = new Handler()
{
public void handleMessage(Message msg)
{
Log.d(appTag, "setting textview");
TextView tv = (TextView) findViewById(R.id.messageText);
tv.setText(mClientMsg);
}
};
class CommsThread implements Runnable
{
public void run()
{
try
{
Socket s = null;
try
{
ss = new ServerSocket(2001);
}
catch (IOException e)
{
Log.d(appTag, e.toString());
}
while (!Thread.currentThread().isInterrupted())
{
Message m = new Message();
Log.d(appTag, "message m = new message()");
try
{
if (s == null) s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
String line = null;
while ((line = in.readLine()) != null)
{
Log.d(appTag, line);
mClientMsg = line;
}
myUpdateHandler.sendMessage(m);
}
catch (IOException e)
{
Log.d(appTag, e.toString());
}
}
}
catch (Exception e)
{
Log.d(appTag, e.toString());
}
}
}
But android application will not receive any data.
can anyone help me to solve my problem?
I'm very noob in socket programming.
sorry for bad english.
thanks.
If you update your reader to just read characters, and spit them out, what does it show? e.g.
try
{
if (s == null) s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
char[] recvd = new char[1];
while (in.read(recvd, 1, 1) != -1)
{
String line = new String(recvd);
Log.d(appTag, line);
mClientMsg = line;
}
myUpdateHandler.sendMessage(m);
}
catch (IOException e)
{
Log.d(appTag, e.toString());
}

Need help with a C# Asynchronous Socket Program that has multiple sends

So, I have a board game that uses Asynchronous socket to operate over LAN. The thing is, I have little to no understanding of Asynchronous socket programming, or of threads, but I do my best to try.
I based my program off a chat program, so I use that part to send multiple strings.
So, here's part of the code for the Client:
private void Connect(IAsyncResult iar)
{
try
{
Socket client_conn = (Socket)iar.AsyncState;
client_conn.EndConnect(iar);
g_bmsg = new byte[1024];
check = true;
string szData = "#Player " + lblName.Text + " connected.";
sendingFunction(szData);
g_client_conn.BeginReceive(g_bmsg, 0, g_bmsg.Length, SocketFlags.None, new AsyncCallback(Receive), g_client_conn);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "GG");
}
}
private void Send(IAsyncResult iar)
{
Socket client_conn = (Socket)iar.AsyncState;
client_conn.EndSend(iar);
}
private void Receive(IAsyncResult iar)
{
if (g_bmsg.Length != 0)
{
SetLabelText(Encoding.ASCII.GetString(g_bmsg, 0, g_bmsg.Length));
check = false;
}
}
private void SetLabelText(string txt)
{
if (lblBuffer.InvokeRequired)
lblBuffer.Invoke(new MethodInvoker(delegate { SetLabelText(txt); }));
else
{
lblBuffer.Text = txt;
}
if (lblBuffer.Text.StartsWith("#"))
{
lblStatmsg.Text = lblBuffer.Text.Replace("#", "");
}
if (lblBuffer.Text.StartsWith("$"))
{
lblStatmsg.Text = "Server Settings Received.";
lblBuffer.Text = lblBuffer.Text.Replace("$", "");
option_Postn = int.Parse(lblBuffer.Text.Substring(0, 1));
option_First = int.Parse(lblBuffer.Text.Substring(2, 1));
}
if (lblBuffer.Text.StartsWith("#"))
{
MessageBox.Show(lblBuffer.Text);
}
}
And here's part of the code for the Server:
private void Accept(IAsyncResult iar)
{
Socket server_conn = (Socket)iar.AsyncState;
g_server_conn = server_conn.EndAccept(iar);
g_bmsg = new byte[1024];
check = true;
g_server_conn.BeginReceive(g_bmsg, 0, g_bmsg.Length, SocketFlags.None, new AsyncCallback(Recieve), g_server_conn);
}
private void Send(IAsyncResult iar)
{
Socket server_conn = (Socket)iar.AsyncState;
server_conn.EndSend(iar);
}
private void Recieve(IAsyncResult iar)
{
try
{
Socket server_conn = (Socket)iar.AsyncState;
server_conn.EndReceive(iar);
if (g_bmsg.Length != 0)
{
SetLabelText(Encoding.ASCII.GetString(g_bmsg, 0, g_bmsg.Length));
check = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "GG");
}
}
private void SetLabelText(string txt)
{
if (lblBuffer.InvokeRequired)
lblBuffer.Invoke(new MethodInvoker(delegate { SetLabelText(txt); }));
else
{
lblBuffer.Text = txt;
}
if (lblBuffer.Text.StartsWith("#"))
{
lblStatmsg.Text = lblBuffer.Text.Replace("#", "");
}
else if (lblBuffer.Text.StartsWith("#"))
{
MessageBox.Show(lblBuffer.Text);
}
else if (lblBuffer.Text.StartsWith("%"))
{
}
}
Basically, since the game sends more than messages (it can send settings, or game pieces, etc), I ran the sender function everytime I need to send something, and on the other side, the Receiver decodes the string sent based on the first character (# means the string is a setting, for example).
The problem is, after the first time both host and client sent something to one another, they can't seem to send again. No error, no message, no nothing. Just won't send. Is there something wrong with the sendingFunction? Or perhaps the delegate something? I don't know. Some advice would be appreciated, guys. And thanks in advance.
You're never calling BeginReceive again. The typical practice in async socket programming is to process the received data, then call BeginReceive again so that you can then process the next bit of data that comes in.

Categories