Hi, I'm relatively new to socket programming and I'm having trouble
understanding them!
I've (using help from tinternet and a useful tutorial) made a client
and server that are able to talk to one another. The problem is when I
start two clients, and send messages to the server from each. Only the
one that was connected first sends the message.
Some code:
Client:
-------------------------------
-------------------------------
public Boolean Connect(String IPAddress)
{
try
{
ClientSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
System.Net.IPAddress ip =
System.Net.IPAddress.Parse(IPAddress);
int iPortNo = Convert.ToInt16(SEND_PORT);
System.Net.IPEndPoint ipEnd = new
System.Net.IPEndPoint(ip.Address, iPortNo);
ClientSocket.Connect(ipEnd);
WaitForData();
}
catch (SocketException se)
{
Console.WriteLine(se.Message);
return false;
}
}
public Boolean SendData(String Data)
{
try
{
Object objData = Data;
byte[] byData =
Encoding.ASCII.GetBytes(objData.ToString());
ClientSocket.Send(byData);
}
.....
}
Server:
-------------------------
-------------------------
public Boolean beginListen()
{
try
{
Listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any,
LISTEN_PORT);
tempEndPoint = (EndPoint)ipLocal;
Listener.Bind(ipLocal);
Listener.Listen(4);
Listener.BeginAccept(new
AsyncCallback(OnClientConnect), null);
}
.....
}
public void OnClientConnect(IAsyncResult asyn)
{
try
{
Worker = Listener.EndAccept(asyn);
WaitForData(Worker);
}
....
}
private void WaitForData(Socket soc)
{
try
{
if (WorkerCallBack == null)
{
WorkerCallBack = new
AsyncCallback(OnDataReceived);
}
CSocketPacket theSocPkt = new CSocketPacket();
theSocPkt.thisSocket = soc;
// now start to listen for any data
soc.BeginReceiveFrom(theSocPkt.dataBuffer, 0,
theSocPkt.dataBuffer.Length, SocketFlags.None, ref tempEndPoint,
WorkerCallBack, theSocPkt);
}
}
private void OnDataReceived(IAsyncResult asyn)
{
try
{
CSocketPacket theSockId =
(CSocketPacket)asyn.AsyncState;
int iRx = 0;
iRx = theSockId.thisSocket.EndReceive(asyn);
char[] chars = new char[iRx + 1];
Decoder d = Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx,
chars, 0);
String szData = new String(chars);
AppendRxText(szData);
WaitForData(Worker);
}
}
I don't quite know what I'm doing, I think I need to allow multiple
socket connections but I've had no luck so far.
Can anyone ched any light on this?
Cheers
Chris