c# How to accept multiple clients in one tcp server - c#

I'm writing a code in c# to have a tcp server that accepts multiple client at the same time. How can I implemet that in my code?
Here is my code, it's in form code. I have a button to start listening, and only accepts one client.
Pd: I'm using Visual Studio 2010.
public partial class Form1 : Form
{
TcpListener mTCPListener;
TcpClient mTCPClient = new TcpClient();
NetworkStream serverStream;
byte[] mRx;
public Form1()
{
InitializeComponent();
}
void onCompleteAcceptTcpClient(IAsyncResult iar)
{
TcpListener tcpl = (TcpListener)iar.AsyncState;
try
{
mTCPClient = tcpl.EndAcceptTcpClient(iar);
printLine("Client Connected...");
//Begin Asynchronous Read
mRx = new byte[1024];
mTCPClient.GetStream().BeginRead(mRx, 0, mRx.Length, onCompleteReadFromTCPClientStream, mTCPClient);
}
catch (Exception exc)
{
MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
void onCompleteReadFromTCPClientStream(IAsyncResult iar)
{
TcpClient tcpc;
int nCountReadBytes = 0;
string strRecv;
try
{
tcpc = (TcpClient)iar.AsyncState;
nCountReadBytes = tcpc.GetStream().EndRead(iar);
if (nCountReadBytes == 0)
{
MessageBox.Show("Client disconnected.");
return;
}
strRecv = Encoding.ASCII.GetString(mRx, 0, nCountReadBytes);
printLine(strRecv);
mRx = new byte[1024];
tcpc.GetStream().BeginRead(mRx, 0, mRx.Length, onCompleteReadFromTCPClientStream, tcpc);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public void printLine(string _strPrint)
{
tbConsoleOutput.Invoke(new Action<string>(doInvoke), _strPrint);
}
public void doInvoke(string _strPrint)
{
tbConsoleOutput.Text = _strPrint + Environment.NewLine + tbConsoleOutput.Text;
}
private void onCompleteWriteToClientStream(IAsyncResult iar)
{
try
{
TcpClient tcpc = (TcpClient)iar.AsyncState;
tcpc.GetStream().EndWrite(iar);
}
catch (Exception exc)
{
MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnStartListening_Click_1(object sender, EventArgs e)
{
try
{
IPAddress ipaddr;
int nPort;
#region Validating IP Address
if (!int.TryParse(tbPort.Text, out nPort))
{
nPort = 23000;
}
if (!IPAddress.TryParse(tbIPAddress.Text, out ipaddr))
{
MessageBox.Show("Invalid IP address supplied.");
return;
}
#endregion
mTCPListener = new TcpListener(ipaddr, nPort);
//Start Listening
mTCPListener.Start();
mTCPListener.BeginAcceptTcpClient(onCompleteAcceptTcpClient, mTCPListener);
}
catch (Exception ex)
{
throw ex;
}
}
private void btnSend_Click_1(object sender, EventArgs e)
{
byte[] tx = new byte[1024];
if (string.IsNullOrEmpty(tbPayload.Text)) return;
try
{
if (mTCPClient != null)
{
if (mTCPClient.Client.Connected)
{
tx = Encoding.ASCII.GetBytes(tbPayload.Text);
mTCPClient.GetStream().BeginWrite(tx, 0, tx.Length, onCompleteWriteToClientStream, mTCPClient);
}
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}

Related

TCP socket timeout

I wrote C# program that server sends data from Server to Client only.
Problem is that time between it sends data is changable ( max 5min)
and that causes sometimes connection to timeout.
When I send data every 3sec then none of them timeouts.
But if message send after 5min then there is problem on Client to recieve it.
I made timeout feature that both Client and Server has. After timeout every reconnects:
public class TimerControl
{
private System.Timers.Timer timeoutTimer = null;
public void initTimeout(int timeMS, System.Timers.ElapsedEventHandler funct)
{
timeoutTimer = new System.Timers.Timer();
timeoutTimer.Interval = timeMS; //MS
timeoutTimer.Elapsed += funct;
timeoutTimer.AutoReset = true;
setTimeoutTimer(false);
}
public void setTimeoutTimer(bool state)
{
if (timeoutTimer != null)
{
timeoutTimer.Stop();
timeoutTimer.Enabled = state;
if (state) timeoutTimer.Start();
}
}
public void resetTimeoutTimer()
{
if (timeoutTimer != null && timeoutTimer.Enabled)
{
timeoutTimer.Stop();
timeoutTimer.Start();
}
}
}
that has not solved the trouble.
What should I do to make it work correct and not timeout after some time?
Server:
public class TCPserver :TCPunit
{
private int TIMEOUT_MS = 5000;
Socket serverListener = null;
Queue<string> dataQueued = null;
bool isConnectedForced = false;
public TCPserver()
{
dataQueued = new Queue<string>();
initTimeout(TIMEOUT_MS, reconnect);
}
public void sendDataToClient(string message)
{
dataQueued.Enqueue(message + Environment.NewLine);
if(isConnectedForced) startListening();
if (dataQueued.Count > 0) setTimeoutTimer(true);
}
public bool connect(string adress)
{
this.thisUnitAdress = adress;
isConnectedForced = true;
loopedConnect();
startListening();
return true;
}
public bool disconnect()
{
isConnectedForced = false;
loopedDisconnect();
return true;
}
private bool loopedConnect()
{
try
{
IPAddress ipAddress = IPAddress.Parse(this.thisUnitAdress);
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port);
if (serverListener != null) loopedDisconnect();
serverListener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
serverListener.Bind(localEndPoint);
Console.WriteLine("SERVER connected to: " + this.thisUnitAdress + " port : " + port.ToString());
return true;
}
catch (Exception ex)
{
Console.WriteLine("!!! SERVER connect");
setTimeoutTimer(true);
return false;
}
}
private bool loopedDisconnect()
{
setTimeoutTimer(false);
if (serverListener != null)
{
if (serverListener.Connected) serverListener.Shutdown(SocketShutdown.Both);
serverListener.Close();
Console.WriteLine("SERVER CLOSED!");
serverListener = null;
}
return true;
}
private void reconnect(Object source, System.Timers.ElapsedEventArgs e)
{
if (isConnectedForced)
{
Console.WriteLine("SERVER RECONNECT!!!");
loopedDisconnect();
loopedConnect();
if (dataQueued.Count > 0) setTimeoutTimer(true);
else setTimeoutTimer(false);
}
else
{
setTimeoutTimer(false);
}
}
private void startListening()
{
try
{
serverListener.Listen(100);
Console.WriteLine("SERVER Waiting for a connection...");
serverListener.BeginAccept(new AsyncCallback(AcceptCallback), serverListener);
setTimeoutTimer(true);
}
catch (Exception ex)
{
Console.WriteLine("!!! SERVER sendingLOOP");
setTimeoutTimer(true);
}
}
private void AcceptCallback(IAsyncResult ar)
{
try
{
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
//HERE SEND
while (dataQueued.Count > 0)
{
string data = dataQueued.Dequeue();
byte[] byteData = Encoding.ASCII.GetBytes(data);
handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
}
//handler.Shutdown(SocketShutdown.Both);
//handler.Close();
setTimeoutTimer(false);
}
catch (Exception ex)
{
Console.WriteLine("!!! SERVER AcceptCallback");
setTimeoutTimer(true);
}
}
private void SendCallback(IAsyncResult ar)
{
try
{
((Socket)ar.AsyncState).EndSend(ar);
}
catch(Exception ex)
{
Console.WriteLine("!!! SERVER SendCallback");
setTimeoutTimer(true);
}
}
}
Client:
public class TCPclient : TCPunit
{
private int TIMEOUT_MS = 5000;
Socket client;
IPEndPoint remoteEP;
bool isConnecting = false;
bool isRecieving = false; // TELS IF PROGRAM SHOULD LOOK FOR SERVER ALL TIME
Action<string> afterRecieveAction = null ; // To print to GUI
public TCPclient()
{
initTimeout(TIMEOUT_MS, reconnect);
}
public void assignAfterRecieveAction(Action<string> action)
{
this.afterRecieveAction = action;
}
public bool connect(string adress)
{
thisUnitAdress = adress;
loopedConnect();
return true;
}
public bool disconnect()
{
isRecieving = false;
isConnecting = false;
loopedDisconnect();
return true;
}
private bool loopedConnect()
{
IPAddress ipAddress = IPAddress.Parse(this.thisUnitAdress);
remoteEP = new IPEndPoint(ipAddress, port);
client = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
setTimeoutTimer(true);
isRecieving = true;
StartClientListening();
return true;
}
private bool loopedDisconnect()
{
if (client != null)
{
if (client.Connected) client.Shutdown(SocketShutdown.Both);
client.Close();
Console.WriteLine("CLIENT CLOSED!");
client = null;
}
return true;
}
private void reconnect(Object source, System.Timers.ElapsedEventArgs e)
{
if (isRecieving)
{
Console.WriteLine("CLIENT RECONNECT!!!");
if (isConnecting) loopedDisconnect();
isRecieving = true;
loopedConnect();
}
}
private void StartClientListening()
{
try
{
if (isRecieving)
{
client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback) , client);
isConnecting = true;
Console.WriteLine("CLIENT listens to: " + thisUnitAdress + " port : " + port.ToString());
}
}
catch (System.Net.Sockets.SocketException ex)
{
Console.WriteLine("CLIENT StartClientListening");
}
catch (Exception ex)
{
Console.WriteLine("!!! CLIENT StartClientListening2");
if (isRecieving) setTimeoutTimer(true);
}
}
private void ConnectCallback(IAsyncResult ar)
{
try
{
client.EndConnect(ar);
Console.WriteLine("CLIENT connected to {0}", client.RemoteEndPoint.ToString());
StateObject state = new StateObject();
state.workSocket = client;
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); ;
}
catch (Exception e)
{
Console.WriteLine("!!! CLIENT ConnectCallback");
if (isRecieving) setTimeoutTimer(true);
}
}
private void ReceiveCallback(IAsyncResult ar)
{
try
{
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
int bytesRead = client.EndReceive(ar);
if (bytesRead > 0)
{
String response = Encoding.ASCII.GetString(state.buffer);
if (afterRecieveAction != null) afterRecieveAction(response);
resetTimeoutTimer();
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
}
catch(System.Net.Sockets.SocketException ex)
{
Console.WriteLine("!!! CLIENT ReceiveCallback");
if (isRecieving) setTimeoutTimer(true);
}
catch(Exception ex)
{
Console.WriteLine("!!! CLIENT ReceiveCallback2");
if (isRecieving) setTimeoutTimer(true);
}
}
}
How to make async Server-Client to work without timeouts?
Best regards,
Chris
You should use socket_set_option to parameter this

Client disconnected, but server don't see it

so i was making a Tcp Server, when i got a problem while a client is disconnecting. Exception is being throwed, but it looks like that server don't see it. And it don't remove the disconnected client from list. Here is code:
public void Read(IAsyncResult ar, TcpClient PL)
{
try
{
{
BytesRead[PL] = PL.GetStream().EndRead(ar);
}
if (BytesRead[PL] < 1)
{
throw new SocketException();
}
else
{
while (true)
{
packets++; break;
}
}
}
catch (Exception x)
{
if ((x.Message.Contains("Client") && x.Message.Contains("Disconnected")) || x is SocketException || x is EndOfStreamException || x is IOException) //|| x.InnerException.GetType() == typeof(IOException))
{
throw;
}
else
{
System.Console.WriteLine(x.ToString());
}
}
}
It occurs when client closes program or when it's killed by task manager
Here is where method Read has been used.
private void HandleClient(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream ns = tcpClient.GetStream();
while (true)
{
try
{
while ((true))
{
{
try
{
}
catch (SocketException ex)
{
if ((ex.Message.Contains("Client") && ex.Message.Contains("Disconnected")) || ex is SocketException)
{
throw;
}
}
try
{
{
}
}
catch (Exception ex)
{
}
}
}
}
catch (SocketException ex)
{
if (((ex.Message.Contains("Client") && ex.Message.Contains("Disconnected"))) || ex is SocketException )
{
clients.Remove(tcpClient);
}
else
{
System.Console.WriteLine(ex.ToString());
}
}
}
}
Here is the TcpListener Initialization
public void Server1()
{
timer = new Timer(new TimerCallback(MultipleCheck), null, 0, 500);
listener = new TcpListener(IPAddress.Parse("25.75.22.56"), 29339);
listenThread = new Thread(new ThreadStart(ListenForClients));
listenThread.Start();
}
And here is method where it accepts the TcpClient
private void ListenForClients()
{
listener.Start();
while (true)
{
System.Console.Title = "Server : " + clients.Count.ToString();
if (!LineStarted)
{
System.Console.WriteLine("Server started on port 29339");
LineStarted = true;
}
System.Console.WriteLine("Connection Request");
TcpClient client = listener.AcceptTcpClient();
if (client.Connected)
{
clients.Add(client);
System.Console.WriteLine("New Client Connected");
//if (threads.ContainsKey(client))
{
threads[client].Start(client);
}
counter++;
}
}
}
Before the threads[tcpClient].Abort(); put try instruction
try
{
//Removing Client from list and notifying connected users about disconnected
//client from list
}
catch
{
}
//And after Abort the thread to avoid the exception of thread aborting being
//thrown too early
threads[tcpClient].Abort();
threads.Remove(tcpClient);

Socket disconnections and gracefully reconnect C#

I am building a tcp port forwarding application. The client connects to the server on a particular port and internally the request is routed in the server to a remote port and response is passed back to the client. Below is my code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace BBGRouter
{
class Router
{
#region log4net
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
#endregion //log4net
bool isShutdown = false;
private Socket router = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public event EventHandler OnRestartNeeded;
//only one time
Thread thRouterTh;
public Router()
{
thRouterTh = new Thread(new ParameterizedThreadStart(RouterProc));
}
IPEndPoint local, remote;
public void Start(IPEndPoint local, IPEndPoint remote)
{
if (log.IsInfoEnabled) { log.Info("Listening on " + local); }
this.local = local;
this.remote = remote;
router.Bind(local);
router.Listen(10);
thRouterTh.Name = "router thread";
thRouterTh.Start();
}
void RouterProc(object obj)
{
while (!isShutdown)
{
try
{
var source = router.Accept();
if (log.IsInfoEnabled) { log.Info("Creating new session...."); }
var destination = new Router();
var state = new State(source, destination.router);
destination.Connect(remote, source);
source.BeginReceive(state.Buffer, 0, state.Buffer.Length, 0, OnDataReceive, state);
}
catch (Exception ex)
{
if (log.IsErrorEnabled) { log.Error("Exception in Router thread", ex); }
if (isShutdown) { if (log.IsInfoEnabled) { log.Info("Shutting down..."); } }
}
}
}
public void Join()
{
if (thRouterTh != null)
thRouterTh.Join();
}
private void StopAndFireRestart(EventArgs e)
{
Stop();
log.Info("Stopped router");
EventHandler handler = OnRestartNeeded;
if (handler != null)
{
log.Info("Firing the restart event now");
handler(this, e);
}
}
public void Stop()
{
try
{
isShutdown = true;
if (log.IsInfoEnabled) { log.Info("Stopping router thread"); }
router.Shutdown(SocketShutdown.Both);
//router.Shutdown(SocketShutdown.Receive);
}
catch (Exception ex)
{
if (log.IsErrorEnabled) { log.Error("Exception while stopping", ex); }
}
finally
{
thRouterTh.Interrupt();
router.Dispose();
}
}
private void Connect(EndPoint remoteEndpoint, Socket destination)
{
if (log.IsInfoEnabled) { log.InfoFormat("connecting session at {0}", remoteEndpoint.ToString()); }
var state = new State(router, destination);
try
{
router.Connect(remoteEndpoint);
router.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, OnDataReceive, state);
}
catch (SocketException e)
{
if (log.IsErrorEnabled) { log.Error(string.Format("SocketException while connect: Exception: {0}, ErrorCode: {1}", e, e.ErrorCode)); }
// Stop the service
StopAndFireRestart(new EventArgs());
}
catch (Exception ex)
{
if (log.IsErrorEnabled) { log.Error("exception while connect {0}", ex); }
}
}
private void OnDataReceive(IAsyncResult result)
{
var state = (State)result.AsyncState;
try
{
var bytesRead = state.SourceSocket.EndReceive(result);
if (bytesRead > 0)
{
log.Info(string.Format("Bytes read: {0}", bytesRead));
state.DestinationSocket.Send(state.Buffer, bytesRead, SocketFlags.None);
state.SourceSocket.BeginReceive(state.Buffer, 0, state.Buffer.Length, 0, OnDataReceive, state);
}
}
catch (Exception e)
{
if (log.IsErrorEnabled) { log.Error("Exception receiving the data, Closing source/destination sockets", e); }
//state.DestinationSocket.Close();
//state.SourceSocket.Close();
//StopAndFireRestart(new EventArgs());
}
}
private class State
{
public Socket SourceSocket { get; private set; }
public Socket DestinationSocket { get; private set; }
public byte[] Buffer { get; private set; }
public State(Socket source, Socket destination)
{
SourceSocket = source;
DestinationSocket = destination;
Buffer = new byte[8192];
}
}
}
}
The problem happens when suddenly the client gets disconnected from the remote port randomly after 4-5 hrs. How can I reconnect the client gracefully so that there is no change in the client code ?
Why don't you solve this issue with netsh?
netsh interface portproxy add v4tov4 listenport=LOCALPORT listenaddress=localhost connectport=REMOTEPORT connectaddress=REMOTEADDRESS
or
netsh interface portproxy add v4tov4 listenport=LOCALPORT connectport=REMOTEPORT connectaddress=REMOTEADDRESS
More information on netsh available on MSDN.

Android TCP communication error

I am very new to Android Programming .
My code in android is as follows
public class AndroidClient extends Activity {
EditText textOut;
TextView textIn;
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_android_client);
textOut = (EditText)findViewById(R.id.textout);
Button buttonSend = (Button)findViewById(R.id.send);
textIn = (TextView)findViewById(R.id.textin);
buttonSend.setOnClickListener(buttonSendOnClickListener);
}
Button.OnClickListener buttonSendOnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
new BackgroundDataTask().execute("");
}};
public class BackgroundDataTask extends AsyncTask<String,String,String> {
private Exception ex;
#Override
protected String doInBackground(String... urls) {
try {
socket = new Socket("10.20.50.68", 8888);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(textOut.getText().toString());
textIn.setText(dataInputStream.readUTF());
socket = serverSocket.accept();
textIn.setText(socket.getInetAddress().toString());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return "";
}
}
}
I have a server in C# Code
The code listens to the port and writes the output
However this only works for the first time when I type in the text and click Send the code is received at Server end and I can see the ouptput in the console,But the value is not received after that .So how can i keep this socket running ? What am I missing?
Thank you All
try this
create a class client.java
public class client{
Socket socket;
int Port;
InetAddress serverIp;
public boolean connection;
public client(String ip, int port) {
// TODO Auto-generated constructor stub
try {
serverIp = InetAddress.getByName(ip);
Port = port;
connect();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
connection = false;
}
}
public void connect(){
try {
System.out.println("wait connection client "+serverIp+" "+Port);
socket = new Socket(serverIp, Port);
connection = true;
} catch (IOException e) {
//e.printStackTrace();
connection = false;
}
}
public boolean send(String message) throws IOException {
byte[] data=message.getBytes();
OutputStream out = socket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
int len = data.length;
dos.writeInt(len);
if (len > 0) {
dos.write(data, 0, len);
}
return true;
}
public String read() {
InputStream in = null;
try {
in = socket.getInputStream();
} catch (IOException e) {
connection=false;
e.printStackTrace();
}
DataInputStream dis = new DataInputStream(in);
try {
int len = dis.readInt();
byte[] data = new byte[len];
if (len > 0) {
dis.readFully(data);
}
String result = new String(data, 0, data.length);
return result;
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
connection=false;
}
return "";
}
and create a object of client.java in your activity onCreate
client con=new client("10.20.50.68", 8888);
and use con.send("your_data") to sent and String data=con.read(); to receive data...
if you want asynchronous listening of data in socket, use thread

Multiple Clients in Client Server app in C#

using resources at http://www.developerfusion.com i came up with the following server code. It works well for single client. How can i make it for multiple clients. I tried adding array and different instances of the beiginreceive but was unable to. The server code:
class Program
{
public static AsyncCallback pfnWorkerCallBack;
public static Socket m_socListener;
public static Socket m_socWorker;
static void Main(string[] args)
{
try
{
//create the listening socket...
m_socListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 8221);
//bind to local IP Address...
m_socListener.Bind(ipLocal);
Console.WriteLine("UCManager Started");
//start listening...
m_socListener.Listen(4);
// create the call back for any client connections...
m_socListener.BeginAccept(new AsyncCallback(OnClientConnect), null);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadLine();
}
public static void OnClientConnect(IAsyncResult asyn)
{
try
{
m_socWorker = m_socListener.EndAccept(asyn);
WaitForData(m_socWorker);
}
catch (Exception se)
{
Console.WriteLine(se.Message);
}
}
public class CSocketPacket
{
public System.Net.Sockets.Socket thisSocket;
public byte[] dataBuffer = new byte[1];
}
public static void WaitForData(System.Net.Sockets.Socket soc)
{
try
{
if (pfnWorkerCallBack == null)
{
pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
}
CSocketPacket theSocPkt = new CSocketPacket();
theSocPkt.thisSocket = soc;
// now start to listen for any data...
soc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, theSocPkt);
}
catch (SocketException se)
{
Console.WriteLine(se.Message);
}
}
public static void OnDataReceived(IAsyncResult asyn)
{
try
{
CSocketPacket theSockId = (CSocketPacket)asyn.AsyncState;
//end receive...
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);
Console.WriteLine(szData);
int code = Convert.ToInt32(szData);
WaitForData(m_socWorker);
}
catch (Exception se)
{
Console.WriteLine(se.Message);
}
}
}
}
EDIT: Ok i did something on the lines of Async TCP Server for multiple Clients.
public static void OnClientConnect(IAsyncResult asyn)
{
try
{
Socket m_socWorkerInstance = m_socListener.EndAccept(asyn);
clientSocketList.Add(m_socWorkerInstance);
WaitForData(m_socWorkerInstance);
}
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
}
catch (SocketException se)
{
Console.WriteLine(se.Message);
}
}
public static void WaitForData(System.Net.Sockets.Socket soc)
{
try
{
if (pfnWorkerCallBack == null)
{
pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
}
CSocketPacket theSocPkt = new CSocketPacket();
theSocPkt.thisSocket = soc;
// now start to listen for any data...
soc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, theSocPkt);
m_socListener.BeginAccept(new AsyncCallback(OnClientConnect), null);
}
catch (SocketException se)
{
Console.WriteLine(se.Message);
}
}
Now i am able to connect two clients but not able to communicate ...I am unable to send message from server to client...any suggestions...also should i have different read functions for both clients if i connect with two client???
You call BeginAccept only once, so after one client has been accepted, your server won't accept any new connections. You should call BeginAccept again after accepting a connection.
Ok i was able to solve it using Async TCP Server for multiple Clients:
public static void OnClientConnect(IAsyncResult asyn)
{
try
{
Socket m_socWorkerInstance = m_socListener.EndAccept(asyn);
clientSocketList.Add(m_socWorkerInstance);
WaitForData(m_socWorkerInstance);
}
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
}
catch (SocketException se)
{
Console.WriteLine(se.Message);
}
}
public static void WaitForData(System.Net.Sockets.Socket soc)
{
try
{
if (pfnWorkerCallBack == null)
{
pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
}
CSocketPacket theSocPkt = new CSocketPacket();
theSocPkt.thisSocket = soc;
// now start to listen for any data...
soc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, theSocPkt);
m_socListener.BeginAccept(new AsyncCallback(OnClientConnect), null);
}
catch (SocketException se)
{
Console.WriteLine(se.Message);
}
}

Categories

Resources