Issue for connecting two sockets - c#

I'm using C# for programming a network application. I'm using a thread to listen an IPEndPoint and answer it.
And another socket to send requests which is using in button handlers. I'm using the TCP protocol.
I've done it many times but today when I was testing it after a long time I understand my application can't connect well.
When I use telnet I can connect to my socket or when I create a test socket I can connect it by my application. There is no strange exception or error and I forward ports by Mono.Nat but problem is not ports because it can communicate with server or client side of itself.
Here is my listening socket code:
public static async void HandleIncomingConnection()
{
await ConfigConnection();
Socket Incomingsockresponde = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint LocalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), StandardPorts[0]);
string NetworkCommandString;
byte[] BytedNetworkString = new byte[1024];
byte[] BytedNetworkFile = new byte[1024 * 100000];
int Len, checker = 0, check = 0;
while(true)
{
try
{
check++;
Incomingsockresponde.Bind(LocalEndPoint);
Incomingsockresponde.Listen(1);
Incomingsockresponde = Incomingsockresponde.Accept();
MessageBox.Show("debug:\n Some remote host connected:" + Incomingsockresponde.RemoteEndPoint.ToString());
MessageBox.Show("Host flagged . . .", "Yeap!");
var mainp = new mainprivate();
mainp.Hstate = "Host not flagged";
try
{
//todo:log stuff
Len = Incomingsockresponde.Receive(BytedNetworkString);
NetworkCommandString = Encoding.ASCII.GetString(BytedNetworkString, 0, Len);
RespondeCommand(NetworkCommandString, Incomingsockresponde);
Incomingsockresponde.Disconnect(true);
}
catch (Exception err)
{
checker++;
MessageBox.Show("Something went wrong with this error:\n" + err.ToString(), "Woops!");
if (checker == 3)
{
MessageBox.Show("Host has some issues for connections", "Woops!");
var main2p = new mainprivate();
main2p.Hstate = "Host has some issues on connections";
return;
}
}
}
catch(Exception err)
{
MessageBox.Show("Something went wrong with this error:\n" + err.ToString(), "Woops!");
if(check == 3)
{
MessageBox.Show("Host not flagged . . .", "Woops!");
var main2p = new mainprivate();
main2p.Hstate = "Host not flagged";
return;
}
if(Incomingsockresponde.Connected == true)
Incomingsockresponde.Disconnect(true);
}
}
}
#endregion
[STAThread]
static void Main()
{
//debug:
MessageBox.Show("Here we go ports :\n" + "ResPort: " + ResPort + "-- - StreamPort:" + StreamPort + "-- - EmerPort:" + EmerPort);
Thread HandleIncomingConnectionThread = new Thread(new ThreadStart(HandleIncomingConnection));
HandleIncomingConnectionThread.Start();
connections[0] = "test";
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new welcome());
}
And this is my request code below:
try
{
Program.availsock.Connect(IPAddress.Parse(haddr[0]), Convert.ToInt16(haddr[1]));
}
catch (Exception err)
{
MessageBox.Show("Can't reach the host" + valstr);
//return;
Program.hostsn--;
addacchost(myKeys[i], valstr, new Size(944, 217), "Uavailable remote host");
goto endsock;
}
//connected
byte[] tmpmssg = new byte[1024];
tmpmssg = Encoding.ASCII.GetBytes(Program.hey);
Program.availsock.Send(tmpmssg);
int tmplng = Program.availsock.Receive(tmpmssg);
string rcdval = Encoding.ASCII.GetString(tmpmssg, 0, tmplng);
haddr = null;
Program.availsock.Close(0);
haddr = rcdval.Split('%');
if (!Program.supporteddistros.Contains(haddr[0]) || !Program.supportedversions.Contains(haddr[1]) || !Program.supportedtypes.Contains(haddr[2]))
{
MessageBox.Show("Unsupported remote host" + valstr);
//delete that from there
Program.oridndic.RemoveAt(checker - 1);
Program.hostsn--;
addacchost(myKeys[i], valstr, new Size(944, 217), "Unsupported remote host");
//acchost.Loadlbl = "Unsupported/Deleted";
//hosts2.Controls.Add(acchost);
//return;
goto endsock;
}
I check ports by netstat -ab and it was listening but it just received connections by telnet or my test socket not request side of my code or reverse my request side just sent request to my test socket.
Is this about my code structure?
Am I making a mistake?
Edit: I also defined a inbound rule for all ports and other stuff for windows firewall.
I'm so confused I never faced this situation I'm just looking for a clue.

Ok well that was just a wrong convert for port i did :
IPEndPoint ep = new IPEndPoint(IPAddress.Parse("0.0.0.0"), Convert.toInt16( port int here));
and it should be :
IPEndPoint ep = new IPEndPoint(IPAddress.Parse("0.0.0.0"), int.Parse(Port int here));
Thanks peoples dont help :/

Related

TCP server and client at once

I am trying to create a blockchain example where all clients work as a server and a client at once. I have a thread which constantly listens for incoming connections and when a client is accepted, it creates a thread which reads the incoming data and sends data aswell. It works one way, for example if just one server is started and I join to it as a client, but for example I want to start 3 instances and start a server on all 3 of them, and then I want to connect to instance 2 from instance 1 and so on... This is the code for acceping clients and the join, host function:
TcpClient Join()
{
int server_port = int.Parse(port.Text);
klient = new TcpClient();
try
{
klient.Connect("localhost", server_port);
if (klient.Connected) //Če se poveže
{
Console.WriteLine("Connected to server.");
myNetworkStream = klient.GetStream();
}
}
catch (Exception e)
{
}
return klient;
}
TcpListener Host()
{
int port = FreeTcpPort();
IPAddress ip_address = IPAddress.Parse("127.0.0.1"); //parsing ipja
TcpListener host = new TcpListener(ip_address, port);//ustvari listener
label1.Text = port.ToString();
try
{
host.Start();//zagon strežnika
Console.WriteLine("Server started...");
mine_button.Enabled = true;
Sprejemaj_cliente = new Thread(Cakaj_na_clienta);
Sprejemaj_cliente.Start(host);
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
return host;
}
public void Cakaj_na_clienta(object argument)
{
TcpListener host = (TcpListener)argument;
try
{
while (true) //ČAKANJE NA POŠILJATELJA
{
Console.WriteLine("Waiting for client...");
TcpClient client = host.AcceptTcpClient();
klient = client;
MessageBox.Show("Client connected");
string odjemalec_IP = ((IPEndPoint)client.Client.RemoteEndPoint).Address.ToString();
int odjemalec_PORT = ((IPEndPoint)client.Client.RemoteEndPoint).Port;
Console.WriteLine("Povezal se je pošiljatelj na naslovu " + odjemalec_IP + ":" + odjemalec_PORT); //Zagon strežnika
myNetworkStream = klient.GetStream();
sync_thread = new Thread(Synchronize);
sync_thread.Start();
send_chain = new Thread(Send_Chain);
send_chain.Start();
}
}
catch (SocketException e)
{
}
}

Connection Reset by Peer C#

So I have windows task scheduler that runs my executable every x minutes.
The executable does the following:
See if any new messages need to sent to the server using sockets.
If there are new messages then make a connection to the server
and send each message.
If there are no new messages then exit the
executable.
Problem:
My executable does not exit and keeps running. So the when windows task scheduler runs again it can't execute because an instance of the executable is still running.
The server where I sent the message told me in the error log they see this:
11-12-19 15:34:09 TCP/IP receive failed; errno 73 - Connection reset by peer.
My code:
namespace TransportMessage
{
class Program
{
static void Main(string[] args)
{
var systemUserId = 1
try
{
using (var dbContext = new DBContext())
{
var unsentRecords = dbContext.Records.Where(x => x.status == "QUEUED").ToList();
if (unsentRecords != null && unsentRecords.Count > 0)
{
var portNumber = 45454;
var dnsName = "xxxx.xxx.xxx.xxx";
IPAddress[] ipAddresses = Dns.GetHostAddresses(dnsName);
Socket soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ipAdd = System.Net.IPAddress.Parse(ipAddresses[0].ToString());
IPEndPoint remoteEP = new IPEndPoint(ipAdd, portNumber);
soc.Connect(remoteEP);
foreach (var rec in unsentRecords)
{
try
{
byte[] byData = System.Text.Encoding.ASCII.GetBytes(rec.message_text);
var numberOfBytesSent = soc.Send(byData);
byte[] buffer = new byte[8000];
int iRx = soc.Receive(buffer);
char[] chars = new char[iRx];
Decoder d = Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(buffer, 0, iRx, chars, 0);
string recv = new string(chars);
rec.sent_ack_message = recv;
rec.number_of_bytes_sent = numberOfBytesSent;
var ackMessageStatus = rec.AckMessageStatus();
if (!String.IsNullOrEmpty(ackMessageStatus))
{
if (ackMessageStatus == "NNN")
{
//Sent successfully. NNN= Good
rec.status = Status.SENT.ToString();
}
else
{
//User received anything else which means something bad in the message.
rec.status = Status.FAILED.ToString();
rec.last_failed_date = DateTime.Now;
rec.last_failed_reason = "Message format incorrect. Please contact IT Operations. Ack Message status " + ackMessageStatus + ".";
}
}
else
{
rec.status = Status.QUEUED.ToString();
rec.last_failed_date = DateTime.Now;
rec.last_failed_reason = "Message sent but no acknowledgment message was received. Message sent back to queued state to try again.";
}
rec.last_modified_by = systemUserId;
rec.last_modified_date = DateTime.Now;
rec.status_date = DateTime.Now;
rec.sent_date = DateTime.Now;
rec.sent_attempt_count = rec.sent_attempt_count + 1;
dbContext.SaveChanges();
}
catch (Exception e)
{
rec.status = Status.FAILED.ToString();
rec.last_modified_by = systemUserId;
rec.last_modified_date = DateTime.Now;
rec.status_date = DateTime.Now;
rec.last_failed_date = DateTime.Now;
rec.last_failed_reason = e.ToString();
rec.sent_attempt_count = rec.sent_attempt_count + 1;
dbContext.SaveChanges();
}
}
}
}
}
catch (System.Net.Sockets.SocketException e)
{
Util.LogError(LogType.FAILED_CONNECTION, e.Message, e.StackTrace);
}
catch (System.Data.DataException e)
{
Util.LogError(LogType.FAILED_TO_CONNECT_TO_DATABASE, e.Message, e.StackTrace);
}
catch (Exception e)
{
//General error if its not database or a socket exception issue.
Util.LogError(LogType.ERROR, e.Message, e.StackTrace);
}
}
}
}
Question:
How do I handle when I get a connection reset by the peer?
I was thinking maybe after I call soc.Connect(remoteEP). I check to see if soc.Connected is false. If so then I disconnect.
if (!soc.Connected)
{
soc.Disconnect(true);
}
Note:
I was disconnecting the socket after I sent my messages but the admin working on the server told me not to do that. Also the executable has been running fine for 3 weeks. No errors or anything.

system.net.sockets.socketexception the remote server closed connection

I have this code on my server side.
public static void Data_IN(object cSocket)
{
Socket clientSocket = (Socket)cSocket;
byte[] Buffer;
int readBytes;
while (true)
{
Buffer = new byte[clientSocket.SendBufferSize];
readBytes = clientSocket.Receive(Buffer);
if (readBytes > 0)
{
Packet p = new Packet(Buffer);
DataManager(p);
}
}
}
And the main problem is that when I stop debugging the code the server always crashes and says
System.Net.Sockets.SocketException: the remote server closed connection
The error is always at readBytes = clientSocket.Recieve(Buffer);
That is the only way I can crash the server, my only concern is when someone uses the chat program that I have created and his/hers computer crashes the chat server will go down and I always need to restart the server.
Clientside code below which executes when closing the window
private void MainWindow_Closed(object sender, EventArgs e)
{
if (isConnected)
{
Packet p = new Packet(PacketType.CloseConnection, ID);
p.data.Add(login);
p.data.Add("exits from chat");
socket.Send(p.ToBytes());
socket.Close();
isConnected = false;
thread.Abort();
}
}
On below there is the code part which uses data_in, that code is on the client side
private void ConnectBtn_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrWhiteSpace(Login.Text))
{
MessageBox.Show("Add username");
}
else if (!IPAddress.TryParse(serverIP.Text, out ipAdress))
{
MessageBox.Show("Add valid ip");
}
else
{
ClearRequireMsg();
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipEndPoint = new IPEndPoint(ipAdress, 4242);
try
{
socket.Connect(ipEndPoint);
login = Login.Text;
isConnected = true;
ConnectBtn.IsEnabled = false;
SendBtn.IsEnabled = true;
thread = new Thread(Data_IN);
thread.Start();
}
catch (SocketException ex)
{
AddMsgToBoard("Error during connecting to server", "System");
}
}
}
You're calling the function Data_IN without passing any parameter.
thread = new Thread(Data_IN);
Right way:
new Thread(() => Data_IN(socket));

Communication between android tablet and PC

I am starting on Android and in my first application I need to establish a communication between and android table a PC. The communication is direct by staqtic IPs as I need that when I have several PCs and tablets each table only communicates with its PC.
The communication from the tablet to the Pc is already working but from the PC to the table I cannot get data transfered
Android side
public class Server implements Runnable
{
#Override
public void run()
{
while (always==true)
{
while(start2==false)
{
}
try
{
InetAddress serverAddr = InetAddress.getByName("192.168.173.133");
updatetrack("\nServer: Start connecting\n");
//*DatagramSocket socket = new DatagramSocket(SERVERPORT2, serverAddr);/
DatagramSocket socket = new DatagramSocket(SERVERPORT2);
byte[] buf = new byte[17];
DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, SERVERPORT2);
//*DatagramPacket packet = new DatagramPacket(buf, buf.length);/
updatetrack("Server: Receiving\n");
socket.receive(packet);
updatetrack("Server: Message received: '" + new String(packet.getData()) + "'\n");
updatetrack("Server: Succeed!\n");
start2=false;
}
catch (Exception e)
{
updatetrack("Server: Error!\n");
start2=false;
}
}
}
}
192.168.173.133 is the table IP and SERVERPORT2 is 4445
When I start the application it remains waiting for data after displaying "Server: Receiving" but
C# code
public static void Main()
{
IPEndPoint iep2 = new IPEndPoint(IPAddress.Parse("192.168.173.133"), 4445);
string hostname = Dns.GetHostName();
byte[] data = Encoding.ASCII.GetBytes(hostname);
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
sock.SendTo(data, iep2);
sock.Close();
}
I suppose that it is any silly think I am forgotten but after reading many forums and books I am stopped on this point
Any advise will be welcome
You use UDP connection and socket.receive(packet) doesn't wait for packet. If there isn't packet in the buffer this operation throw exception.
Try to change your code to:
#Override
public void run()
{
while (always==true)
{
while(start2==false)
{
}
try
{
InetAddress serverAddr = InetAddress.getByName("192.168.173.133");
updatetrack("\nServer: Start connecting\n");
//*DatagramSocket socket = new DatagramSocket(SERVERPORT2, serverAddr);/
DatagramSocket socket = new DatagramSocket(SERVERPORT2);
while (always==true)
{
try{
byte[] buf = new byte[17];
DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, SERVERPORT2);
//*DatagramPacket packet = new DatagramPacket(buf, buf.length);/
updatetrack("Server: Receiving\n");
socket.receive(packet);
updatetrack("Server: Message received: '" + new String(packet.getData()) + "'\n");
updatetrack("Server: Succeed!\n");
start2=false;
}
catch(Exception ex) {ex.printStackTrace();}
}
}
catch (Exception e)
{
updatetrack("Server: Error!\n");
start2=false;
}
}
}

Chat service application

I am making a chat service for a game,
I am using a TCP listener an client for the account information, some sort of login service. I'm wondering if i can keep the socked the client connected to the server with, to check if he is still online, and keep sending him messages if he has new messages.
I already tried making a list of sockets for the login queue, but it disconnected the previous socket to to server as soon as i accepted a new socket.
byte[] usernameByte = new byte[100];
int usernameRecieved = s.Receive(usernameByte);
//guiController.setText(System.DateTime.Now + " Recieved Login...");
byte[] passByte = new byte[100];
int passRecieved = s.Receive(passByte);
//guiController.setText(System.DateTime.Now + " Recieved Password...");
string username = "";
string password = "";
for (int i = 0; i < usernameRecieved; i++)
username += (Convert.ToChar(usernameByte[i]));
for (int i = 0; i < passRecieved; i++)
password += (Convert.ToChar(passByte[i]));
if (DomainController.getInstance().checkAccount(username, password))
{
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("true"));
s.Send(asen.GetBytes("U are succesfully logged in, press enter to continue"));
guiController.setText(serverName,System.DateTime.Now+"");
guiController.setText(serverName, "Sent Acknowledgement - Logged in");
}
else
{
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("false"));
s.Send(asen.GetBytes("U are NOT logged in, press enter to continue"));
guiController.setText(serverName, System.DateTime.Now + "");
guiController.setText(serverName, "\nSent Acknowledgement - Not logged in");
}
This is the code i currently use to check the account information the user send me. Right after i send this the user dropd the connection and i move on to the next one.
I have tried making 1 list of seperate sockets and processing them one by one, but that failed because the previous socket's connection dropped, even tho it were 2 different machines that tried to connect.
Does anyone have a sollution / a way to save sockets, that I can use to make the program keep all the connections alive? so i can send a message from user 1 to user 2, and just use the socket they connected with? or do i need to add an id every time they make a connection?
EDIT
The client Code: (this is just a test client)
while (true)
{
TcpClient tcpclnt = new TcpClient();
Console.WriteLine("Connecting.....");
tcpclnt.Connect("xx.xxx.xxx.xx", 26862);
// use the ipaddress as in the server program
while(!(checkResponse(tcpclnt.GetStream())))
{
Thread.Sleep(1000);
}
Console.WriteLine("Connected");
Console.Write("Enter the string to be transmitted : ");
String str = Console.ReadLine();
if (str == "")
{
str = " ";
}
Stream stm = tcpclnt.GetStream();
ASCIIEncoding asen = new ASCIIEncoding();
byte[] ba = asen.GetBytes(str);
Console.WriteLine("Transmitting.....");
stm.Write(ba, 0, ba.Length);
Console.Write("Enter the string to be transmitted : ");
String str2 = Console.ReadLine();
if (str2 == "")
{
str2 = " ";
}
Stream stm2 = tcpclnt.GetStream();
ASCIIEncoding asen2 = new ASCIIEncoding();
byte[] ba2 = asen2.GetBytes(str2);
Console.WriteLine("Transmitting.....");
stm.Write(ba2, 0, ba2.Length);
if (str == "false")
{
blijvenWerken = false;
}
byte[] bb = new byte[100];
int k = stm.Read(bb, 0, 100);
for (int i = 0; i < k; i++)
Console.Write(Convert.ToChar(bb[i]));
byte[] bb2 = new byte[100];
int k2 = stm.Read(bb2, 0, 100);
Console.Write("\n");
for (int i = 0; i < k2; i++)
Console.Write(Convert.ToChar(bb2[i]));
Console.WriteLine("\n");
tcpclnt.Close();
Thread.Sleep(1000);
}
Server getting the sockets:
This bit of code is on the loginserver, its because i can only accept 1 socket every time to keep the connection alive, that i put queueCount on a maximum of 1.
I want to be able to make a list of Sockets that i accepted to add to a User account.
while (loginServerOn)
{
if (queueCount < 1)
{
if (loginServer.getLoginListener().Pending())
{
loginQueue.Add(loginServer.getSocket());
ASCIIEncoding asen = new ASCIIEncoding();
Socket s = loginQueue.First();
try
{
s.Send(asen.GetBytes("true"));
queueCount++;
}
catch
{
loginQueue.Remove(s);
}
}
}
}
The function that returns the accepted socket.
public Socket getSocket()
{
return myList.AcceptSocket();
}
EDIT: Essence of the question
I want to add the socked or client recieved to my Account object, so every connection has an Account its linked to, when i want to send a message to a certain account, it should send a message to the socked or client bound to that account, can you help/show me how i can achieve this?
This is still c# and sockets but my approach is different to yours.
I went with the concept of a "connectedCleint" which is similar in purpose to what you've called an account.
I have a class called ServerTerminal which is responsible for accepting and top level management of socket connections. In this i've got:
public Dictionary<long, ConnectedClient> DictConnectedClients =
new Dictionary<long, ConnectedClient>();
So this is my list of connected clients indexed by the sockethandle.
To accept connections i've got a routine:
public void StartListen(int port)
{
socketClosed = false;
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, port);
listenSocket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
//bind to local IP Address...
//if ip address is allready being used write to log
try
{
listenSocket.Bind(ipLocal);
}
catch (Exception excpt)
{
// Deal with this.. write your own log code here ?
socketClosed = true;
return;
}
//start listening...
listenSocket.Listen(100); // Max 100 connections for my app
// create the call back for any client connections...
listenSocket.BeginAccept(new AsyncCallback(OnClientConnection), null);
}
So when a client connects it then fires off:
private void OnClientConnection(IAsyncResult asyn)
{
if (socketClosed)
{
return;
}
try
{
Socket clientSocket = listenSocket.EndAccept(asyn);
ConnectedClient connectedClient = new ConnectedClient(clientSocket, this, _ServerTerminalReceiveMode);
//connectedClient.MessageReceived += OnMessageReceived;
connectedClient.Disconnected += OnDisconnection;
connectedClient.dbMessageReceived += OndbMessageReceived;
connectedClient.ccSocketFaulted += ccSocketFaulted;
connectedClient.StartListening();
long key = clientSocket.Handle.ToInt64();
if (DictConnectedClients.ContainsKey(connectedClient.SocketHandleInt64))
{
// Already here - use your own error reporting..
}
lock (DictConnectedClients)
{
DictConnectedClients[key] = connectedClient;
}
// create the call back for any client connections...
listenSocket.BeginAccept(new AsyncCallback(OnClientConnection), null);
}
catch (ObjectDisposedException excpt)
{
// Your own code here..
}
catch (Exception excpt)
{
// Your own code here...
}
}
The crucial part of this for you is:
// create the call back for any client connections...
listenSocket.BeginAccept(new AsyncCallback(OnClientConnection), null);
This sets up the serverterminal to receive new connections.
Edit:
Cut down version of my connectedclient:
public class ConnectedClient
{
private Socket mySocket;
private SocketIO mySocketIO;
private long _mySocketHandleInt64 = 0;
// These events are pass through; ConnectedClient offers them but really
// they are from SocketIO
public event TCPTerminal_ConnectDel Connected
{
add
{
mySocketIO.Connected += value;
}
remove
{
mySocketIO.Connected -= value;
}
}
public event TCPTerminal_DisconnectDel Disconnected
{
add
{
mySocketIO.Disconnected += value;
}
remove
{
mySocketIO.Disconnected -= value;
}
}
// Own Events
public event TCPTerminal_TxMessagePublished TxMessageReceived;
public delegate void SocketFaulted(ConnectedClient cc);
public event SocketFaulted ccSocketFaulted;
private void OnTxMessageReceived(Socket socket, TxMessage myTxMessage)
{
// process your message
}
private void OnMessageSent(int MessageNumber, int MessageType)
{
// successful send, do what you want..
}
public ConnectedClient(Socket clientSocket, ServerTerminal ParentST)
{
Init(clientSocket, ParentST, ReceiveMode.Handler);
}
public ConnectedClient(Socket clientSocket, ServerTerminal ParentST, ReceiveMode RecMode)
{
Init(clientSocket, ParentST, RecMode);
}
private void Init(Socket clientSocket, ServerTerminal ParentST, ReceiveMode RecMode)
{
ParentServerTerminal = ParentST;
_myReceiveMode = RecMode;
_FirstConnected = DateTime.Now;
mySocket = clientSocket;
_mySocketHandleInt64 = mySocket.Handle.ToInt64();
mySocketIO = new SocketIO(clientSocket, RecMode);
// Register for events
mySocketIO.TxMessageReceived += OnTxMessageReceived;
mySocketIO.MessageSent += OnMessageSent;
mySocketIO.dbMessageReceived += OndbMessageReceived;
}
public void StartListening()
{
mySocketIO.StartReceiving();
}
public void Close()
{
if (mySocketIO != null)
{
mySocketIO.Close();
mySocketIO = null;
}
try
{
mySocket.Close();
}
catch
{
// We're closing.. don't worry about it
}
}
public void SendMessage(int MessageNumber, int MessageType, string Message)
{
if (mySocket != null && mySocketIO != null)
{
try
{
mySocketIO.SendMessage(MessageNumber, MessageType, Message);
}
catch
{
// mySocketIO disposed inbetween check and call
}
}
else
{
// Raise socket faulted event
if (ccSocketFaulted != null)
ccSocketFaulted(this);
}
}
}
}
Some useful links:
This is where I started:
http://vadmyst.blogspot.com.au/2008/01/how-to-transfer-fixed-sized-data-with.html
http://vadmyst.blogspot.com.au/2008/03/part-2-how-to-transfer-fixed-sized-data.html
And..
C# Sockets and Multithreading
Cause a connected socket to accept new messages right after .BeginReceive?
http://nitoprograms.blogspot.com.au/2009/04/tcpip-net-sockets-faq.html
http://www.codeproject.com/Articles/83102/C-SocketAsyncEventArgs-High-Performance-Socket-Cod
I can't post my entire solution just now; there is a flaw in my server code I need to debug; plus there are parts which my employer may not want published. But i based my code on what Vadym had for variable length messages.
When a server gets ready to accept TCP connections, it creates a new TCP socket, Bind() it to a port and uses the Listen() method. When a connection request comes in, the Listen() method returns a new socket that the server and client use for communication. The server and client can pass data back and forth using Send() and Receive() at this point. If the client disconnects, the server's Receive() terminates with 0 bytes of data.
If you want to wait for another connection request once you've accepted the first connection (i.e., while you are interacting with the first client) this can be done. At this point, you'll need to use something like threads or asynchronous methods so you can handle more than one connection. Basically, you will be able to Accept() connection requests from your listening socket.
Mike

Categories