C# Sockets


Recommended Posts

I have been working on Socket Network Connections I have a problem with the receive string not updating, but in debugger I see the values being assigned to it change.

This is all done in sharp develop so I will attach the project, inside is socketclient.exe which is the client side for testing. (that was done by the example page,

http://www.codeguru.com/csharp/csharp/cs_m...icle.php/c7695/

when I build it like the example (all one class) it works but it not teh right way as you have to throw a

CheckForIllegalCrossThreadCalls = false; so .net 2 will not throw an error about the gui being updated out side its thread.

so I fixed that by putting the socket code in its own class, and creating a timer to look at the variables

in lines 162 - 178 of SocketConnect.cs is the part on receive.

here is the class

/*
* Created by SharpDevelop.
* User: huskeyw
* Date: 12/11/2006
* Time: 4:52 PM
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/

using System;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;

namespace socket_server
{
/// <summary>
/// Description of SocketConnect.
/// </summary>
public class SocketConnect
{
const int MaxClients = 10;
Socket mainSocket;
Socket [] workerSocket = new Socket[MaxClients];
int clientCount = 0;
public AsyncCallback callBack;
string temp = "";
errors Errors = new errors();

List<string> IpAddress = new List<string>();
List<string> data = new List<string>();

string status;

public string Status {
get {
return status;
}
set {
status = value;
}
}
string recvMesg = "";

public string RecvMesg {
get {
return recvMesg;
}
set {
recvMesg = value;
}
}
string sendMesg;

public string SendMesg {
get {
return sendMesg;
}
set {
sendMesg = value;
}
}



public SocketConnect()
{

}

/// <summary>
///
/// </summary>
/// <param name="PortNumber"></param>
public bool Listen(int PortNumber)
{
try
{
mainSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
//connect to ipaddress
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, PortNumber);
//bind to ipaddress
mainSocket.Bind(ipLocal);
//listen on ipaddress
mainSocket.Listen(4);

//when a connection comes in invoke method OnClientConnect
mainSocket.BeginAccept(new AsyncCallback (OnClientConnect), null);
return true;

}
catch (SocketException se)
{
Errors.SocketError(se.Message);
}
return false;
}



public void OnClientConnect(IAsyncResult asyn)
{
try
{
workerSocket[clientCount] = mainSocket.EndAccept (asyn);

WaitForData(workerSocket[clientCount]);

++clientCount;

string str = string.Format("Client# {0} Connected", clientCount);
Status = str;

mainSocket.BeginAccept(new AsyncCallback (OnClientConnect),null);
}
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0,"1","\n OnClientConnection: Socket has been Closed\n");

}
catch(SocketException se)
{
Errors.SocketError(se.Message);
}
}

public class SocketPacket
{
public System.Net.Sockets.Socket currentSocket;
public byte[] databuffer = new byte[1];
}

public void WaitForData(System.Net.Sockets.Socket socket)
{
try
{
if(callBack == null)
{
callBack = new AsyncCallback (OnDataReceived);
}

SocketPacket socketPacket = new SocketPacket();
socketPacket.currentSocket = socket;

socket.BeginReceive (socketPacket.databuffer, 0,
socketPacket.databuffer.Length,
SocketFlags.None,
callBack,
socketPacket);

}
catch(SocketException se)
{
Errors.SocketError(se.Message);
}

}

public void OnDataReceived(IAsyncResult asyn)
{
try
{
SocketPacket socketData = (SocketPacket)asyn.AsyncState;
int iRx = 0;


iRx = socketData.currentSocket.EndReceive(asyn);
char[] recivedSocketData = new char[iRx + 1];

System.Text.Decoder decodeText = System.Text.Encoding.UTF8.GetDecoder();

int charLen = decodeText.GetChars(socketData.databuffer, 0, iRx, recivedSocketData,0);

System.String szData = new System.String(recivedSocketData);
//why does not not work...
//recvMesg is a class level variable
this.RecvMesg += recivedSocketData;

WaitForData( socketData.currentSocket);

}
catch(ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0,"1","\nOnDataReceived: Socket has been closed\n");
}
catch (SocketException se)
{
Errors.SocketError(se.Message);
}

}

public void send(string rtbSendMsg)
{
try
{
Object objData = rtbSendMsg;
byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());

for (int i = 0; i < clientCount; i++)
{
if(workerSocket[i] != null)
{
if(workerSocket[i].Connected)
{
workerSocket[i].Send (byData);
}
}
}
}
catch(SocketException se)
{
Errors.SocketError(se.Message);

}
}

public void CloseSockets()
{
if(mainSocket != null)
{
mainSocket.Close();
}

for(int i = 0; i < clientCount; i++)
{
if(workerSocket[1] != null)
{
workerSocket[i].Close();
workerSocket[i] = null;
}

}
}

public string[] GetIP()
{
string strHostName = Dns.GetHostName();

IPHostEntry ipHostEntry = Dns.GetHostEntry(strHostName);


foreach (IPAddress ipaddress in ipHostEntry.AddressList)
{

IpAddress.Add(ipaddress.ToString());
}

string [] returnString = new String[IpAddress.Count];
for (int x = 0; x < IpAddress.Count;x++)
{
returnString[x] = IpAddress[x];
}
return returnString;
}

}
}

and here is where the problem is (I think)

public void OnDataReceived(IAsyncResult asyn)
{
try
{
SocketPacket socketData = (SocketPacket)asyn.AsyncState;
int iRx = 0;


iRx = socketData.currentSocket.EndReceive(asyn);
char[] recivedSocketData = new char[iRx + 1];

System.Text.Decoder decodeText = System.Text.Encoding.UTF8.GetDecoder();

int charLen = decodeText.GetChars(socketData.databuffer, 0, iRx, recivedSocketData,0);

System.String szData = new System.String(recivedSocketData);
//why does not not work...
//recvMesg is a class level variable
this.RecvMesg += recivedSocketData;

WaitForData( socketData.currentSocket);

}
catch(ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0,"1","\nOnDataReceived: Socket has been closed\n");
}
catch (SocketException se)
{
Errors.SocketError(se.Message);
}

}

PS I just finished my degree for CIS in programing (does it show:) ) so thanks to all of you on this board for helping me when I was in need.

socket_server2.zip

Edited by iccaros
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...