SocketAsync, can't reconnect to server - c#

I have a problem with my Socketasync application, I have a server, and a client (the code below), everything with the communication works great except when the server application is closed, then the client cant reconnect. If I restart the client, its no problem at all, to connect again, but it has to be restarted. So my question is how I can modify this code, to help it reconnect without restarting the application it self.
This is the connection code!
public Client()
{
try
{
this.ip = ini.GetFromIni("CONFIG", "IP");
this.port = ini.GetFromIni("CONFIG", "PORT");
data = new byte[60000];
receiveBuffer = new byte[60000];
this.hostEndPoint = new IPEndPoint(IPAddress.Parse(this.ip), Convert.ToInt32(port));
this.clientSocket = new Socket(this.hostEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
// Instantiates the endpoint and socket.
startTimer = new System.Timers.Timer();
startTimer.Elapsed += new ElapsedEventHandler(startSendLoop);
startTimer.Interval = 1000;
startTimer.Start();
sendTimer = new System.Timers.Timer();
sendTimer.Elapsed += new ElapsedEventHandler(sendloop);
sendTimer.Interval = 500;
sendTimer.Start();
}
catch (Exception e)
{
}
}
public void startSendLoop(object sender, ElapsedEventArgs e)
{
try
{
startTimer.Interval = 10000;
startTimer.Enabled = false;
if (!this.clientSocket.Connected)
{
this.hostEndPoint = new IPEndPoint(IPAddress.Parse(this.ip), Convert.ToInt32(port));
this.clientSocket = new Socket(this.hostEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
if (connectArgs != null)
connectArgs.Dispose();
connectArgs = new SocketAsyncEventArgs();
connectArgs.UserToken = this.clientSocket;
connectArgs.RemoteEndPoint = this.hostEndPoint;
connectArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnConnect);
clientSocket.ConnectAsync(connectArgs);
bool test = autoConnectEvent.WaitOne(5000);
gotData = true;
lastTime = DateTime.Now;
}
startTimer.Enabled = true;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
¨
More code if someone wants to see it... not directly linked to the connection.
private void OnConnect(object sender, SocketAsyncEventArgs e)
{
autoConnectEvent.Set();
// Set the flag for socket connected.
this.connected = (e.SocketError == SocketError.Success);
}
private void OnSend(object sender, SocketAsyncEventArgs e)
{
// Signals the end of send.
sendSuccess = true;
autoSendReceiveEvents[ReceiveOperation].Set();
if (e.SocketError == SocketError.Success)
{
if (e.LastOperation == SocketAsyncOperation.Send)
{
// Prepare receiving.
//Socket s = e.UserToken as Socket;
for (int i = 0; i < receiveBuffer.Length; i++)
{
if (receiveBuffer[i] != 0)
receiveBuffer[i] = 0;
else
break;
}
e.SetBuffer(receiveBuffer, 0, receiveBuffer.Length);
e.Completed += new EventHandler<SocketAsyncEventArgs>(OnReceive);
clientSocket.ReceiveAsync(e);
//sendloop();
}
}
else
{
this.ProcessError(e);
}
}
private void OnReceive(object sender, SocketAsyncEventArgs e)
{
try
{
while (true)
{
if (this.canReceive)
{
canReceive = false;
string stringData;
int recv = 0;
for (int i = 0; i < e.Buffer.Length; i++)
{
if (e.Buffer[i] != 0)
recv++;
else
break;
}
if (recv > 0)
{
Console.WriteLine(recv.ToString());
int count = 0;
for (int i = 0; i < data.Length; i++)
{
if (data[i] != 0)
count++;
else
break;
}
e.Buffer.CopyTo(data, count);
//currentData = Encoding.UTF8.GetString(e.Buffer, 0, recv);
lastTime = DateTime.Now;
gotData = true;
if ((byte)data[count + recv - 1] == (byte)255)
{
int cnt = -1;
for (int i = 0; i < count + recv; i++)
{
if (data[i] == (byte)254)
{
cnt = i;
break;
}
}
int nr = (count + recv) - cnt - 2;
byte[] tmp = new byte[nr];
for (int i = 0; i < nr; i++)
{
tmp[i] = data[cnt + i + 1];
}
string crc = Encoding.Default.GetString(tmp);
stringData = Encoding.Default.GetString(data, 0, cnt);
MsgStruct msgs = new MsgStruct(stringData);
msgs.setCrc(crc);
todo.Add(msgs);
for (int i = 0; i < data.Length; i++)
{
if (data[i] != 0)
data[i] = 0;
else
break;
}
allreadyGot = false;
handleToDo();
// Signals the end of receive.
}
}
autoSendReceiveEvents[SendOperation].Set();
Socket s = e.UserToken as Socket;
canReceive = true;
break;
}
else
{
Thread.Sleep(10);
}
}
}
catch (Exception ex)
{
canReceive = true;
}
}
private void ProcessError(SocketAsyncEventArgs e)
{
Socket s = e.UserToken as Socket;
if (s.Connected)
{
// close the socket associated with the client
try
{
s.Shutdown(SocketShutdown.Both);
}
catch (Exception)
{
// throws if client process has already closed
}
finally
{
if (s.Connected)
{
s.Close();
}
}
}
// Throw the SocketException
//throw new SocketException((Int32)e.SocketError);
}
public void sendloop(object sender, ElapsedEventArgs e)
{
try
{
if (this.clientSocket.Connected)
{
sendTimer.Enabled = false;
bool waitExtra = false;
DateTime tmpDate = lastTime.AddSeconds(30);
if (DateTime.Now > tmpDate && tmpDate != DateTime.MinValue)
{
gotData = false;
}
if(sendSuccess)
{
canUseBuffert = false;
if (msgHand.gotMsg() && data[0] == 0)
{
if (msgHand.getNextMsg() != null && msgHand.getNextMsg().getMsg().Length != 0)
{
byte[] ba = Encoding.Default.GetBytes(msgHand.getNextMsg().getMsg());
if (msgHand.getNextMsg().getCrc() == "")
{
ulong tmp = CRC.calc_crc(ba, ba.Length);
msgHand.getNextMsg().setCrc(tmp.ToString("X"));
}
if (msgHand.getNextMsg().canSendByTimeout())
{
string crcStr = "?" + msgHand.getNextMsg().getCrc() + "?";
byte[] bb = Encoding.Default.GetBytes(crcStr);
crcStr = Encoding.Default.GetString(bb);
byte[] fullMsg = new byte[ba.Length + bb.Length];
bb[0] = 254;
bb[bb.Length - 1] = 255;
ba.CopyTo(fullMsg, 0);
bb.CopyTo(fullMsg, ba.Length);
string s = System.Text.Encoding.Default.GetString(fullMsg);
completeArgs = new SocketAsyncEventArgs();
completeArgs.SetBuffer(fullMsg, 0, fullMsg.Length);
completeArgs.UserToken = this.clientSocket;
completeArgs.RemoteEndPoint = this.hostEndPoint;
completeArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnSend);
sendSuccess = false;
// Start sending asyncronally.
clientSocket.SendAsync(completeArgs);
// Wait for the send/receive completed.
//AutoResetEvent.WaitAll(autoSendReceiveEvents);
// Return data from SocketAsyncEventArgs buffer.
//stm.Write(fullMsg, 0, fullMsg.Length);
if (!msgHand.getNextMsg().isAckNeeded())
msgHand.removeNextMsgs();
}
}
}
else
{
waitExtra = true;
byte[] bba = Encoding.Default.GetBytes("X");
completeArgs = new SocketAsyncEventArgs();
completeArgs.SetBuffer(bba, 0, bba.Length);
completeArgs.UserToken = this.clientSocket;
completeArgs.RemoteEndPoint = this.hostEndPoint;
completeArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnSend);
sendSuccess = false; //Dessa ska in även i den andra applikationen
// Start sending asyncronally.
clientSocket.SendAsync(completeArgs);
// Wait for the send/receive completed.
//AutoResetEvent.WaitAll(autoSendReceiveEvents);
}
}
canUseBuffert = true;
//if (!clientSocket.Connected && !gotData)
//Disconnect();
}
sendTimer.Enabled = true;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
sendTimer.Enabled = true;
}
}
internal void Disconnect()
{
clientSocket.Disconnect(true);
}
public void Dispose()
{
autoConnectEvent.Close();
autoSendReceiveEvents[SendOperation].Close();
autoSendReceiveEvents[ReceiveOperation].Close();
if (this.clientSocket.Connected)
{
this.clientSocket.Close();
}
}
public void handleToDo()
{
//handle msg
}

Related

C# Windows service - Run two void methods

Can anyone help me with Windows service in C#?
I used topshelf to create windows service. I have issue with run two methods together. When I run app via in console, it works. But when I try to run in windows service, it's don't work together like I need.
First I start communication with OPC DA server and second I want start TCP Listerner
public void Start()
{
try
{
T1 = new Thread(new ThreadStart(DoOpc));
T1.Start();
T2 = new Thread(new ThreadStart(TcpConn));
T2.Start();
}
catch (Exception e)
{
Program.LogEntry("Error", e.ToString(), "Fatal");
}
}
Methods:
public static void TcpConn()
{
try
{
Program.LogEntry("TCP Comm", "Theard start...");
Int32 port = Int32.Parse(ConfigurationManager.AppSettings["TCP_port"]);
IPAddress localAddr = IPAddress.Parse(ConfigurationManager.AppSettings["TCP_IP"]);
TcpServer = new TcpListener(localAddr, port);
TcpServer.Start();
const int bytesize = 2048 * 2048; // Constant, not going to change later
Byte[] bytes = new Byte[bytesize];
String data = null;
while (true)
{
TcpClient client = TcpServer.AcceptTcpClient();
IPAddress TcpIPClient = ((IPEndPoint)(client.Client.RemoteEndPoint)).Address;
NetworkStream stream = client.GetStream();
data = null;
Program.LogEntry("TCP Comm", "Connected! IP: " + TcpIPClient);
int i;
if (StopTcp == true)
{
Program.LogEntry("Service status", "Stoping TCP server...");
client.Close();
client.GetStream().Close();
TcpServer.Stop();
break;
}
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Program.LogEntry("TCP Comm", "Received: " + data);
string output = ProccessData(data);
byte[] msg = System.Text.Encoding.ASCII.GetBytes(output);
Program.LogEntry("TCP Comm", "Output: " + output);
stream.Write(msg, 0, msg.Length);
}
stream.Close();
client.Close();
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e.ToString());
Program.LogEntry("TCP Comm", "SocketException: " + e.ToString(), "Fatal");
}
finally
{
Console.WriteLine("TCP: bye bye");
Program.LogEntry("TCP Comm", "Bye Bye", "Warning");
TcpServer.Stop();
System.Environment.Exit(6);
}
}
OPC
private static void DoOpc()
{
try
{
URL url = new URL(ConfigurationManager.AppSettings["OPC_Server"]);
OpcServer = new Opc.Da.Server(new OpcCom.Factory(), url);
OpcServer.Connect();
if (OpcServer.IsConnected == true)
{
Program.LogEntry("OPC Client", "Connected !");
}
else
{
Program.LogEntry("OPC Client", "NOT Connected!", "Fatal");
}
OpcServer.ServerShutdown += new Opc.ServerShutdownEventHandler(OnServerShutdown);
// Evidencia groupy/channelu ------Create group
Opc.Da.SubscriptionState state = new Opc.Da.SubscriptionState();
state.ClientHandle = 0;
//state.Name = "Device1";
state.UpdateRate = 500;
state.Active = true; // true;
Opc.Da.Subscription group = (Opc.Da.Subscription)OpcServer.CreateSubscription(state);
// Callback on Data change
group.DataChanged += new Opc.Da.DataChangedEventHandler(OnDataChange);
Opc.Da.Item NewItem;
List<Opc.Da.Item> NewItems = new List<Opc.Da.Item>();
foreach (var item in ActiveItems.Where(x => x.Active == true))
{
NewItem = new Opc.Da.Item();
NewItem.ClientHandle = 0;
NewItem.ItemName = item.Device + "." + item.Tag; //int4 = 32 bit
NewItems.Add(NewItem);
}
Item[] Items = NewItems.ToArray();
ItemResult[] ir = group.AddItems(Items);
SubscriptionState activatestate = group.GetState();
activatestate.Active = true;
group.ModifyState((int)Opc.Da.StateMask.Active, activatestate);
TcpConn();
}
catch (Exception e)
{
Program.LogEntry("Error with OPC connection", e.ToString(), "Fatal");
}
}

Client-server app turns off after logging

In my C# server-client program I have following isue:
after logging to server with one of clients server automatically goes off with StackOverFlowException after connecting with IP and typing "LOGIN xxxxxxx".
Client code
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace SIKTcpClient
{
class Program
{
private const int Port = 3000;
private static Socket _socket;
private const int attemptsLimit = 2;
private const int BufferSize = 2048;
private static byte[] buffer = new Byte[BufferSize];
private static string _login;
static void Main(string[] args)
{
Console.WriteLine("Write ip adress");
var input = Console.ReadLine();
var ipAdress = input.Length < 2 ? GetIpAdress() : input;
if (input.Length < 2)
Console.WriteLine(ipAdress);
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Connect(ipAdress);
Console.WriteLine("Your login");
try
{
if (input.Length < 2)
{
Console.WriteLine(_login);
_socket.Send(Encoding.ASCII.GetBytes(_login));
}
while (true)
{
var result = Console.ReadLine();
var bytes = Encoding.ASCII.GetBytes(result);
_socket.Send(bytes);
}
}
catch (SocketException)
{
Console.WriteLine("Server was shut down.");
}
catch(Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
}
static void Connect(string ipAdress)
{
var attempts = 0;
while (!_socket.Connected && attempts < attemptsLimit)
{
try
{
++attempts;
var result = _socket.BeginConnect(ipAdress, Port, EndConnect, null);
result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(3));
Thread.Sleep(3000);
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex.Message}");
}
}
if(!_socket.Connected)
{
Console.WriteLine("Could not connect to server");
return;
}
}
private static void EndConnect(IAsyncResult asyncResult)
{
try
{
_socket.EndConnect(asyncResult);
if (_socket.Connected)
{
_socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), _socket);
}
else
{
Console.WriteLine("End of connection attempt, fail to connect...");
}
}
catch (SocketException)
{
Console.WriteLine("Waiting for server...");
}
catch(Exception ex)
{
Console.WriteLine("Cant connnect to server... " + ex.Message);
}
}
private static void ReceiveCallback(IAsyncResult asyncResult)
{
try
{
var socket = (Socket)asyncResult.AsyncState;
if (socket.Connected)
{
var received = socket.EndReceive(asyncResult);
if (received > 0)
{
var data = new byte[received];
Buffer.BlockCopy(buffer, 0, data, 0, data.Length);
var message = Encoding.UTF8.GetString(data);
if (!string.IsNullOrWhiteSpace(message))
Console.Write("Server: " + Encoding.UTF8.GetString(data));
socket.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
}
}
}
catch(SocketException)
{
Console.WriteLine("Server was shut down.");
}
catch(Exception ex)
{
Console.WriteLine("Receive callback failed "+ ex.Message);
}
}
private static string GetIpAdress()
{
var random = new Random();
var r = random.Next(100000000);
_login = "LOGIN " + r;
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
socket.Connect("8.8.8.8", 65530);
var endPoint = socket.LocalEndPoint as IPEndPoint;
var localIP = endPoint.Address.ToString();
return localIP;
}
}
}
}
server code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using SIKTcpServer.Constants;
using SIKTcpServer.Models;
using SIKTcpServer.Models.Cards;
namespace SIKTcpServer
{
class Program
{
private static Socket _socket;
private const int Port = 3000;
private const int BufferSize = 2048;
private static byte[] _buffer = new byte[BufferSize];
private static List<Player> _players = new List<Player>();
private static bool _gameStarted = false;
private static List<Player> _playersInRound;
private static readonly int[] _ids = new int[5] { 1, 2, 3, 4, 5 };
private static List<AbstractCard> _turnCards;
static void Main(string[] args)
{
Console.Title = "Server";
GatherPlayers();
Console.ReadKey();
}
private static void GatherPlayers()
{
//var a = LoadCards();
Console.WriteLine("Waiting for players...");
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_socket.Bind(new IPEndPoint(IPAddress.Any, Port));
_socket.Listen(0);
_socket.BeginAccept(new AsyncCallback(AcceptCallback), null);
while(_players.Count < 2) { }
Console.WriteLine("asd");
}
private static void AcceptCallback(IAsyncResult asyncResult)
{
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
socket = _socket.EndAccept(asyncResult);
if (_players.Count > 2 || _gameStarted)
{
socket.Send(GetAsciiBytes("Sorry we have 5 players already"));
return;
}
socket.Send(GetAsciiBytes("CONNECT"));
Console.WriteLine("Connected new socket");
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
_socket.BeginAccept(new AsyncCallback(AcceptCallback), socket);
}
catch
{
RemovePlayer(socket);
socket.Dispose();
}
}
private static void ReceiveCallback(IAsyncResult asyncResult)
{
Socket current = (Socket)asyncResult.AsyncState;
int received;
try
{
received = current.EndReceive(asyncResult);
}
catch (SocketException)
{
Console.WriteLine("Client forcefully disconnected");
current.Close();
RemovePlayer(current);
return;
}
byte[] recBuffer = new byte[received];
Array.Copy(_buffer, recBuffer, received);
string text = Encoding.ASCII.GetString(recBuffer);
Console.WriteLine("Received Text: " + text);
if (_players.Count > 4)
{
current.Send(GetAsciiBytes("Sorry we have 5 players already"));
current.Close();
current.Dispose();
}
else if (text.Length < 7 || text.Substring(0, 5) != "LOGIN" || string.IsNullOrWhiteSpace(text.Substring(6, 2)))
{
Console.WriteLine("Text is an invalid request");
var data = Encoding.ASCII.GetBytes("Invalid request");
current.Send(data);
Console.WriteLine("Warning Sent");
current.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, ReceiveCallback, current);
}
else
{
current.Send(GetAsciiBytes("OK"));
_players.Add(new Player(current));
Console.WriteLine("Player OK");
}
}
private static void Round()
{
StartRound();
while (_playersInRound.Count > 1 && _turnCards.Count > 0)
{
foreach (var player in _playersInRound)
{
if (player.IsEliminated)
{
}
if (player.SkipTurn)
{
player.SkipTurn = false;
continue;
}
var card = GetRandomCard();
player.Cards.Add(card);
player.Socket.Send(GetAsciiBytes($"YOUR MOVE {card.Name}"));
var playerCardsNames = player.Cards.Select(x => x.Name).ToArray();
if (player.HaveCountessAndKingOrPrince)
{
while(true)
{
player.Socket.Receive(_buffer, 0, _buffer.Length, SocketFlags.None);
}
}
var splittedMessage = GetStringFromBytes(_buffer).Split(new char[0]);
var choosenPlayer = Int32.Parse(splittedMessage[2] ?? "0");
var choosenSecondCard = splittedMessage[3] ?? "";
var playedCard = player.Cards.Where(x => x.Name.ToString() == splittedMessage[1]).First();
player.Cards.Where(x => x.Name == playedCard.Name).FirstOrDefault().Action(player, _playersInRound.Where(x => x.Id == choosenPlayer).FirstOrDefault(), choosenSecondCard);
//Array.Clear(_buffer, 0, _buffer.Length);
RemoveEliminatedPlayers();
}
}
}
private static void StartRound()
{
MixPlayers();
LoadCards();
GiveStartingCardsToPlayers();
foreach (var player in _playersInRound)
{
player.Socket.Send(GetAsciiBytes($"START {player.Id.ToString()} {player.Cards[0]}"));
}
}
private static void MixPlayers()
{
var ids = _ids.ToList();
var random = new Random();
for (var i = 0; i < 5; i++)
{
var randomListIndex = random.Next(ids.Count);
_playersInRound[i].Id = ids[randomListIndex];
ids.RemoveAt(randomListIndex);
}
_playersInRound.OrderBy(x => x.Id);
}
private static void RemovePlayer(Socket socket)
{
_players.Remove(_players.Where(x => x.Socket == socket).FirstOrDefault());
}
private static List<AbstractCard> LoadCards()
{
var allCards = new List<AbstractCard>();
var values = Enum.GetValues(typeof(CardName)).Cast<CardName>().ToArray();
foreach (var value in values)
{
for (var i = 0; i < (int)Enum.Parse(typeof(CardAmount), value.ToString()); i++)
{
switch (value)
{
case CardName.Baron:
allCards.Add(new BaronCard());
break;
case CardName.Countess:
allCards.Add(new CountessCard());
break;
case CardName.Guard:
allCards.Add(new GuardCard());
break;
case CardName.Handmaiden:
allCards.Add(new HandmaidenCard());
break;
case CardName.King:
allCards.Add(new KingCard());
break;
case CardName.Priest:
allCards.Add(new PriestCard());
break;
case CardName.Prince:
allCards.Add(new PrinceCard());
break;
case CardName.Princess:
allCards.Add(new PrincessCard());
break;
}
}
}
return allCards;
}
private static AbstractCard GetRandomCard()
{
var random = new Random();
var randomIndex = random.Next(_turnCards.Count);
var randomCard = _turnCards[randomIndex];
_turnCards.RemoveAt(randomIndex);
return randomCard;
}
private static void GiveStartingCardsToPlayers()
{
foreach (var player in _playersInRound)
{
player.Cards.Add(GetRandomCard());
}
}
private static void RemoveEliminatedPlayers()
{
Predicate<Player> eliminated = (Player player) => { return player.IsEliminated == true; };
_playersInRound.RemoveAll(eliminated);
_players.ForEach(x => x.ClearElimination());
}
private static byte[] GetAsciiBytes(string text)
{
return Encoding.ASCII.GetBytes(text);
}
private static string GetStringFromBytes(byte[] bytes)
{
return Encoding.ASCII.GetString(bytes);
}
}
}
Sadly stackoverflow site says that it looks like my post is mostly code but i have described everything above so sorry for this pointless text here.
you have created the static buffer array which is giving you out stackoverflow exception this is because multiple clients requesting at the same time. they used this static buffer for both. it is not a good in development creating static buffer.
you have to comes up with some new login like this.
public class SocketPacketforROD
{
public System.Net.Sockets.Socket CurrentSocket;
//test
public int last_buffer_read = 0;
public int last_socket_payload_size = 0;
public byte[] Data = null; // new byte[Server.bufferLength];
public SocketPacketforROD_State m_state = SocketPacketforROD_State.socket_state_payload_size;
public void allocate(int bytes)
{
// socket_buffer_length = bytes;
Data = new byte[bytes];
}
}
Used this socket object class in your onreceiveddata method
string Data = Encoding.ASCII.GetString(socketData.Data);
Logger.WriteLog("Message Received length : " + Data.Length + " from: " + socketData.CurrentSocket.RemoteEndPoint, LogLevel.GENERALLOG);
socketData.m_state = SocketPacketforROD_State.socket_state_payload_size;
Setup Receive callback
private void SetupReceiveCallback(Socket objClientSocket)
{
try
{
AsyncCallback recieveData = new AsyncCallback(OnRecievedData);
SocketPacketforROD theSocPkt = new SocketPacketforROD();
theSocPkt.last_socket_payload_size = 4;
theSocPkt.allocate(4);
theSocPkt.CurrentSocket = objClientSocket;
Logger.WriteLog("After New Socket buffer Length : " + theSocPkt.Data.Length, LogLevel.GENERALLOG);
objClientSocket.BeginReceive(theSocPkt.Data, 0, theSocPkt.Data.Length, SocketFlags.None, recieveData, theSocPkt);
}
catch (OutOfMemoryException MemEXP)
{
Logger.WriteException(MemEXP);
}
catch (Exception E)
{
Logger.WriteException(E);
}
}

Cannot access a disposed Object C#

I am having a hard time. I am new to this. Can someone help me with this. Every time I call the _clientSocket.Close(); I got an error message.
Cannot access a disposed object. Object name:
System.net.Sockets.Socket
There's no error in my code. It can run smooth but every time I open and close a form it comes up. I want to get rid of it. The program can run with it but its to irritating. Because when I try to open a client it will pop up. And when the time of the client is done, the form will close and the login will come out with another pop up of
Cannot access a disposed object. Object name:
System.net.Sockets.Socket
I use _clientSocket.Close() because if I'm not closing the sockets it will be doubled in Server side. I close it so it will not be double IP in Checklistbox of the Server.
I'm doing this for my project and I'm just studying myself so some of the comments I really don't understand but I'm trying my best to learn from it thank you!
Your suggestions will much appreciated. Correct me if I'm wrong thank you!
This code is the Loginform when Server sends -O it will _clientSocket.Close(); and open the Form2. If Form2 use all the time it will back to Loginform and form2 _clientSocket.Close(); I call the _clientSocket.Close(); because the Server Checklistbox that catches all the connected sockets will be doubled if I don't close the Sockets.
Edited
Server
namespace RealVersion2
{
public partial class Server : Form
{
public class SocketT2h
{
public Socket _Socket { get; set; }
public string _Name { get; set; }
public SocketT2h(Socket socket)
{
this._Socket = socket;
}
}
private byte[] _buffer = new byte[1024];
public List<SocketT2h> __ClientSockets { get; set; }
List<string> _names = new List<string>();
private Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public Server()
{
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
__ClientSockets = new List<SocketT2h>();
this.list_Client.SelectionMode = System.Windows.Forms.SelectionMode.None;
}
private void Send_Click(object sender, EventArgs e)
{
{
for (int i = 0; i < list_Client.CheckedItems.Count; i++)
{
string t = list_Client.CheckedItems[i].ToString();
for (int j = 0; j < __ClientSockets.Count; j++)
{
if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("#" + t))
{
Sendata(__ClientSockets[j]._Socket, "Server: " );
}
else
{
Sendata(__ClientSockets[j]._Socket, "Server: " + txt_Text.Text);
}
}
}
rich_Text.AppendText("\nServer: " + txt_Text.Text);
txt_Text.Text = "";
}
}
void Sendata(Socket socket, string noidung)
{
byte[] data = Encoding.ASCII.GetBytes(noidung);
socket.BeginSend(data, 0, data.Length, SocketFlags.None, new AsyncCallback(SendCallback), socket);
_serverSocket.BeginAccept(new AsyncCallback(AppceptCallback), null);
}
private void SendCallback(IAsyncResult AR)
{
Socket socket = (Socket)AR.AsyncState;
socket.EndSend(AR);
}
private void SetupServer()
{
try
{
lb_stt.Text = "Setting up server . . .";
_serverSocket.Bind(new IPEndPoint(IPAddress.Any, 8000));
_serverSocket.Listen(1);
_serverSocket.BeginAccept(new AsyncCallback(AppceptCallback), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AppceptCallback(IAsyncResult ar)
{
Socket socket = _serverSocket.EndAccept(ar);
__ClientSockets.Add(new SocketT2h(socket));
list_Client.Items.Add(socket.RemoteEndPoint.ToString());
lb_soluong.Text = "Number of clients connected: " + __ClientSockets.Count.ToString();
lb_stt.Text = "Client connected. . .";
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
_serverSocket.BeginAccept(new AsyncCallback(AppceptCallback), null);
}
private void ReceiveCallback(IAsyncResult ar)
{
Socket socket = (Socket)ar.AsyncState;
if (socket.Connected)
{
int received;
try
{
received = socket.EndReceive(ar);
}
catch (Exception)
{
// client close connection
for (int i = 0; i < __ClientSockets.Count; i++)
{
if (__ClientSockets[i]._Socket.RemoteEndPoint.ToString().Equals(socket.RemoteEndPoint.ToString()))
{
//taga tapoon ng panget
list_Client.Items.RemoveAt(i);
__ClientSockets.RemoveAt(i);
lb_soluong.Text = "Number of clients connected: "+__ClientSockets.Count.ToString();
}
}
//delete in list
return;
}
if (received!=0)
{
byte[] dataBuf = new byte[received];
Array.Copy(_buffer, dataBuf, received);
string text = Encoding.ASCII.GetString(dataBuf);
//lb_stt.Text = "Text received: " + text;
string reponse = string.Empty;
//reponse = "Server: Hi! You're Connected to the Librarian.";
if (text.Contains("##"))
{
for (int i = 0; i < list_Client.Items.Count; i++)
{
if (socket.RemoteEndPoint.ToString().Equals(__ClientSockets[i]._Socket.RemoteEndPoint.ToString()))
{
list_Client.Items.RemoveAt(i);
list_Client.Items.Insert(i, text.Substring(1, text.Length - 1));
__ClientSockets[i]._Name = text;
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
return;
}
}
}
for (int i = 0; i < __ClientSockets.Count; i++)
{
if (socket.RemoteEndPoint.ToString().Equals(__ClientSockets[i]._Socket.RemoteEndPoint.ToString()))
{
rich_Text.AppendText("\n" + __ClientSockets[i]._Name + ": " + text);
}
}
}
else
{
for (int i = 0; i < __ClientSockets.Count; )
{
if (__ClientSockets[i]._Socket.RemoteEndPoint.ToString().Equals(socket.RemoteEndPoint.ToString()))
{
__ClientSockets.RemoveAt(i);
lb_soluong.Text ="The number of clients connected: " + __ClientSockets.Count.ToString();
}
}
}
}
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), socket);
}
private void tabPage1_Click(object sender, EventArgs e)
{
}
private void Server_Load(object sender, EventArgs e)
{
SetupServer();
}
private void Restartbtn_Click(object sender, EventArgs e)
{
string Restart = string.Empty;
Restart = "-r";
{
for (int i = 0; i < list_Client.CheckedItems.Count; i++)
{
string t = list_Client.CheckedItems[i].ToString();
for (int j = 0; j < __ClientSockets.Count; j++)
{
if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("#" + t))
{
Sendata(__ClientSockets[j]._Socket, "Server: " + Restart);
}
}
}
rich_Text.AppendText("\nServer: " + txt_Text.Text);
}
}
private void Shutdownbtn_Click(object sender, EventArgs e)
{
string Shutdown = string.Empty;
Shutdown = "-s";
{
for (int i = 0; i < list_Client.CheckedItems.Count; i++)
{
string t = list_Client.CheckedItems[i].ToString();
for (int j = 0; j < __ClientSockets.Count; j++)
{
if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("#" + t))
{
Sendata(__ClientSockets[j]._Socket, "Server: " + Shutdown);
}
}
}
rich_Text.AppendText("\nServer: " + txt_Text.Text);
}
}
private void list_Client_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < list_Client.Items.Count; i++)
{
if (list_Client.GetItemRectangle(i).Contains(list_Client.PointToClient(MousePosition)))
{
switch (list_Client.GetItemCheckState(i))
{
case CheckState.Checked:
list_Client.SetItemCheckState(i, CheckState.Unchecked);
break;
case CheckState.Indeterminate:
case CheckState.Unchecked:
list_Client.SetItemCheckState(i, CheckState.Checked);
break;
}
}
}
}
private void openPCToolStripMenuItem_Click_1(object sender, EventArgs e)
{
string Open = string.Empty;
Open = "-O";
{
for (int i = 0; i < list_Client.CheckedItems.Count; i++)
{
string t = list_Client.CheckedItems[i].ToString();
for (int j = 0; j < __ClientSockets.Count; j++)
{
if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("#" + t))
{
Sendata(__ClientSockets[j]._Socket, "Server: " + Open);
//use [i] if u dont want name in list
}
}
}
//rich_Text.AppendText("\nServer: " + txt_Text.Text);
}
}
private void Server_FormClosing(object sender, FormClosingEventArgs e)
{
string Ext = string.Empty;
Ext = "exit";
{
for (int i = 0; i < list_Client.CheckedItems.Count; i++)
{
string t = list_Client.CheckedItems[i].ToString();
for (int j = 0; j < __ClientSockets.Count; j++)
{
if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("#" + t))
{
Sendata(__ClientSockets[j]._Socket, "Server: " + Ext);
}
}
}
//rich_Text.AppendText("\nServer: " + txt_Text.Text);
Application.Exit();
_serverSocket.Close();
}
}
private void End_Click(object sender, EventArgs e)
{
string Ext = string.Empty;
Ext = "close";
{
for (int i = 0; i < list_Client.CheckedItems.Count; i++)
{
string t = list_Client.CheckedItems[i].ToString();
for (int j = 0; j < __ClientSockets.Count; j++)
{
if (__ClientSockets[j]._Socket.Connected && __ClientSockets[j]._Name.Equals("#" + t))
{
Sendata(__ClientSockets[j]._Socket, "Server: " + Ext);
}
}
}
//rich_Text.AppendText("\nServer: " + txt_Text.Text);
}
}
}
}
Client
public partial class UserLog : Form
{
private Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
TimeSpan countdownClock = TimeSpan.Zero;
public UserLog()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string Username = "User";
string Pass = "123";
if (Username == textBox1.Text && Pass == textBox2.Text)
{
MessageBox.Show("Login Successfully");
Usertimer User = new Usertimer(textBox1.Text);
User.Show();
this.Hide();
_clientSocket.Dispose();
_clientSocket.Close();
}
else
{
MessageBox.Show("Please Enter valid Username or Password");
}
}
byte[] receivedBuf = new byte[1024];
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
if (_clientSocket != null && _clientSocket.Connected)
{
_clientSocket.Close();
}
}
private void ReceiveData(IAsyncResult ar)
{
try
{
int received = _clientSocket.EndReceive(ar);
if (received == 0)
{
return;
}
Array.Resize(ref receivedBuf, received);
string text = Encoding.Default.GetString(receivedBuf);
Array.Resize(ref receivedBuf, _clientSocket.ReceiveBufferSize);
AppendtoTextBox(text);
if (text == "Server: -O")
{
Thread NT = new Thread(() =>
{
this.BeginInvoke((Action)delegate ()
{
textBox1.Text = "Guest";
this.Hide();
_clientSocket.Close();
Usertimer us = new Usertimer(textBox1.Text);
us.Show();
});
});
NT.Start();
}
if (text == "Server: exit")
{
_clientSocket.Close();
Application.Exit();
}
_clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), null);
}
catch (ObjectDisposedException ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AppendtoTextBox(string text)
{
MethodInvoker invoker = new MethodInvoker(delegate
{
textBox4.Text += text + "\r\n";
});
this.Invoke(invoker);
}
private void LoopConnect()
{
int attempts = 0;
while (!_clientSocket.Connected)
{
try
{
attempts++;
_clientSocket.Connect(IPAddress.Parse(textBox5.Text), 8000);
//_clientSocket.Connect(IPAddress.Parse(textBox4.Text), 100);
}
catch (SocketException)
{
//Console.Clear();
lb_stt.Text = ("Connection attempts: " + attempts.ToString());
}
}
AppendtoTextBox(reponse);
}
private void button2_Click(object sender, EventArgs e)
{
LoopConnect();
// SendLoop();
_clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), _clientSocket);
byte[] buffer = Encoding.ASCII.GetBytes("##"+txName.Text);
_clientSocket.Send(buffer);
}
private void UserLog_Load(object sender, EventArgs e)
{
LoopConnect();
_clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), _clientSocket);
byte[] buffer = Encoding.ASCII.GetBytes("##"+txName.Text);
_clientSocket.Send(buffer);
}
private void UserLog_FormClosed(object sender, FormClosedEventArgs e)
{
Application.Exit();
}
}
}
Form2 of the client
public partial class Usertimer : Form
{
private Socket _clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public Usertimer(string pass)
{
InitializeComponent();
label3.Text = pass;
}
byte[] receivedBuf = new byte[1024];
protected override void OnShown(EventArgs e)
{
base.OnShown(e);
this.btnConnect_Click(null, null);
}
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
if (_clientSocket != null && _clientSocket.Connected)
{
_clientSocket.Close();
}
}
private void ReceiveData(IAsyncResult ar)
{
try
{
int received = _clientSocket.EndReceive(ar);
if (received == 0)
{
return;
}
Array.Resize(ref receivedBuf, received);
string text = Encoding.Default.GetString(receivedBuf);
if (text == "Server: close")
{
Thread NT = new Thread(() =>
{
this.BeginInvoke((Action)delegate ()
{
UserLog Log = new UserLog();
Log.Show();
this.Close();
_clientSocket.Close();
});
});
NT.Start();
}
Array.Resize(ref receivedBuf, _clientSocket.ReceiveBufferSize);
AppendtoTextBox(text);
_clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), null);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void AppendtoTextBox(string text)
{
MethodInvoker invoker = new MethodInvoker(delegate
{
richTextBox1.Text += text + "\r\n";
});
this.Invoke(invoker);
}
private void LoopConnect()
{
int attempts = 0;
while (!_clientSocket.Connected)
{
try
{
attempts++;
_clientSocket.Connect(IPAddress.Parse(textBox4.Text), 8000);
}
catch (SocketException)
{
//Console.Clear();
lb_stt.Text = ("Connection attempts: " + attempts.ToString());
}
}
AppendtoTextBox(reponse);
}
private void btnConnect_Click(object sender, EventArgs e)
{
LoopConnect();
// SendLoop();
_clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), _clientSocket);
byte[] buffer = Encoding.ASCII.GetBytes("##" + txName.Text);
_clientSocket.Send(buffer);
}
private void btnSend_Click(object sender, EventArgs e)
{
if (_clientSocket.Connected)
{
byte[] buffer = Encoding.ASCII.GetBytes(txt_text.Text);
_clientSocket.Send(buffer);
AppendtoTextBox(txName.Text + ": " + txt_text.Text);
}
txt_text.Text = "";
}
private void button1_Click(object sender, EventArgs e)
{
UserLog log = new UserLog();
log.Show();
this.Close();
_clientSocket.Close();
}
}
}
Like I answered in your previous question, you should spend the time to read these two pages. They will help you get your answer much faster.
There's no error in my code.
If you're getting an error message, then there's an error in your code.
every time I open and close a form
What form? There is no form in your example.
it will be doubled in Server side. I close it so it will not be double IP in Checklistbox of the Server.
What server? What checklistbox? We don't know what you are referring to here.
Without a minimal, complete and verifiable example, we can't help you very well. That being said, it looks like you are closing your _clientSocket. Once you've closed a socket you must re-open it or create a new one before you can use it again. You cannot call BeginReceive after you've closed your socket.
I was able to reproduce your error by creating a complete, minimal and verifiable example. Here is the code:
public partial class Form1 : Form
{
Socket _clientSocket;
public Form1()
{
InitializeComponent();
}
const int buffSize = 1024;
byte[] receivedBuf = new byte[buffSize];
Socket listenerSock;
Socket handlerSock;
private void Form1_Load(object sender, EventArgs e)
{
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
listenerSock = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
listenerSock.Bind(localEndPoint);
listenerSock.Listen(10);
listenerSock.BeginAccept(ServerAcceptAsync, null);
_clientSocket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
_clientSocket.Connect(localEndPoint);
_clientSocket.BeginReceive(receivedBuf, 0, buffSize, SocketFlags.None, ReceiveData, null);
}
private void ServerAcceptAsync(IAsyncResult ar)
{
handlerSock = listenerSock.EndAccept(ar);
}
private void ReceiveData(IAsyncResult ar)
{
//try
//{
Debug.WriteLine("received data");
int received = _clientSocket.EndReceive(ar);
if (received == 0)
{
return;
}
Array.Resize(ref receivedBuf, received);
string text = Encoding.Default.GetString(receivedBuf);
Debug.WriteLine(text);
if (text == "Server: -O")
{
Thread NT = new Thread(() =>
{
this.BeginInvoke((Action)delegate ()
{
textBox1.Text = "Guest";
this.Hide();
_clientSocket.Close();
//Usertimer us = new Usertimer(textBox1.Text);
//us.Show();
});
});
NT.Start();
}
Array.Resize(ref receivedBuf, _clientSocket.ReceiveBufferSize);
//AppendtoTextBox(text);
_clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), null);
//}
//catch (Exception ex)
//{
// MessageBox.Show(ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Error);
//}
}
private void button1_Click(object sender, EventArgs e)
{
var message = Encoding.UTF8.GetBytes("Server: -O");
handlerSock.Send(message);
}
}
I commented the code that was not necessary to reproduce. As expected, the problem is that you call ReceiveAsync after you call _clientSock.Close(). You can't do that. If you close the socket, you should not execute anymore code. Here is an example of how to fix this:
if (text == "Server: -O")
{
Thread NT = new Thread(() =>
{
this.BeginInvoke((Action)delegate ()
{
textBox1.Text = "Guest";
this.Hide();
_clientSocket.Close();
//Usertimer us = new Usertimer(textBox1.Text);
//us.Show();
});
});
NT.Start();
}
else
{
Array.Resize(ref receivedBuf, _clientSocket.ReceiveBufferSize);
//AppendtoTextBox(text);
_clientSocket.BeginReceive(receivedBuf, 0, receivedBuf.Length, SocketFlags.None, new AsyncCallback(ReceiveData), null);
}

C# Received data from SerialPort is wrong after writing

I have a communication device which sends requests every two seconds through COM. Between the requests, the device waits for response. I'm building software in C# with SerialPort. I call an event handler for data receiving and I run a method in new thread with while loop which checks that the request is as expected and calls method responsible for response. The thing is, after response next received data is wrong. Here is the code:
The SerialPortManager:
class SerialPortManager : IDisposable
{
...
public void connect()
{
if (mSerialPort.IsOpen)
return;
mSerialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
try
{
mSerialPort.Open();
}
catch (Exception e)
{
MessageBox.Show(e.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
mStatus = Status.DISCONNECTED;
return;
}
if (mSerialPort.IsOpen)
{
mStatus = Status.CONNECTED;
Thread tryToResponseThread = new Thread(tryToResponse);
tryToResponseThread.Start();
}
}
private void tryToResponse()
{
while (mStatus == Status.CONNECTED)
{
if (mRequest.Length >= 56)
{
string checksum = "555555555555555580808080";
if (mRequest.Length > 56)
{
mRequest.Remove(55, mRequest.Length - 56);
Debug.Print("cutting");
}
if (mRequest.ToString().StartsWith(checksum))
{
StringBuilder strToCMD = new StringBuilder();
for (int i = 0; i < mRequest.Length; i += 2)
{
strToCMD.Append(mRequest[i]);
strToCMD.Append(mRequest[i + 1]);
strToCMD.Append(" ");
}
StringBuilder address = new StringBuilder();
StringBuilder group = new StringBuilder();
address.Append(mRequest.ToString(24, 8));
group.Append(mRequest.ToString(24 + 8, 2));
mMainForm.appendCMDTextboxText(Environment.NewLine);
mMainForm.appendCMDTextboxText(DateTime.Now.ToLongTimeString() + " [RX] " + address.ToString() + " " + group.ToString() + "\t");
mMainForm.appendCMDTextboxText(strToCMD.ToString());
byte[] request = ByteArrayConverter.fromString16(mRequest.ToString());
mRequest.Clear();
response(request);
Array.Clear(request, 0, request.Length);
Debug.Print("starts with checksum");
}
else if (mRequest.ToString().Contains(checksum))
{
int indexOfChecksum = mRequest.ToString().IndexOf(checksum);
mRequest.Remove(0, indexOfChecksum);
Debug.Print("contains");
}
else
{
int index = 0;
bool found = false;
for (int i = 0; i < checksum.Length; i++)
{
StringBuilder s = new StringBuilder();
int sub = mRequest.Length - checksum.Length + i + 2;
if (sub == mRequest.Length)
break;
s.Append(mRequest.ToString().Substring((Math.Max(0, mRequest.Length - checksum.Length + i + 2))));
s.Append(mRequest.ToString(0, i + 2));
if (s.ToString().Equals(checksum))
{
index = sub;
found = true;
break;
}
}
if (found)
{
mRequest.Remove(0, index);
}
else
{
mRequest.Clear();
}
Debug.Print("on start and end");
}
}
}
}
private void response(byte[] request)
{
Luminaire lumToResponse = mLuminaireManager.getLuminaire(request);
if (lumToResponse == null)
{
return;
}
else
{
if (lumToResponse.isNotResponding())
return;
}
byte[] responseMsg = lumToResponse.getWholeFrame(request);
mMainForm.setCommandLabelForResponsingLuminaire(lumToResponse);
mMainForm.appendCMDTextboxText(Environment.NewLine + DateTime.Now.ToLongTimeString() + " [TX]\t");
string responseMsgAsString = ByteArrayConverter.toString(responseMsg).Replace("-", " ");
mMainForm.appendCMDTextboxText(responseMsgAsString);
write(responseMsg, 0, responseMsg.Length);
mSerialDataEventArgs.clearData();
}
public void write(byte[] buffer, int offset, int count)
{
if (mStatus == Status.DISCONNECTED || mSerialPort.IsOpen == false)
{
mStatus = Status.DISCONNECTED;
return;
}
mSerialPort.Write(buffer, offset, count);
}
void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (mStatus == Status.DISCONNECTED)
return;
int dataLength = mSerialPort.BytesToRead;
if (dataLength == 0)
return;
byte[] data = new byte[dataLength];
mSerialPort.Read(data, 0, dataLength);
mSerialDataEventArgs.setData(data);
mDataReceived?.Invoke(this, mSerialDataEventArgs);
}
...
}
The helpser class for passing the received data:
public class SerialDataEventArgs : EventArgs
{
public SerialDataEventArgs()
{
}
public void setData(byte[] data)
{
clearData();
mData = data;
}
public SerialDataEventArgs(byte[] dataInByteArray)
{
mData = dataInByteArray;
}
public void clearData()
{
if (mData == null)
return;
Array.Clear(mData, 0, mData.Length);
}
public byte[] mData;
}
And the main class:
public partial class MainForm : Form
{
...
private void MainForm_Load(object sender, EventArgs e)
{
mSerialPortManager = new SerialPortManager();
mSerialPortManager.setPortBoudRate((int)numUpDown_SerialPortSpeed.Value);
mLuminaireManager = new LuminaireManager();
mSerialPortManager.mMainForm = this;
mSerialPortManager.mLuminaireManager = mLuminaireManager;
fixTableLayoutColumnSize(ref tl_SingleLuminaire);
fillTheRestOfSingleLuminaireGroupBoxes();
fillSerialPortComboBoxWithNamesOfAvailablePorts();
mSerialPortManager.mDataReceived += new EventHandler<SerialDataEventArgs>(serialPortManager_DataReceived);
mIsPaused = false;
}
private void serialPortManager_DataReceived(object sender, SerialDataEventArgs e)
{
if (this.InvokeRequired)
{
this.BeginInvoke(new EventHandler<SerialDataEventArgs>(serialPortManager_DataReceived), new object[] { sender, e });
return;
}
if (mIsPaused)
return;
mSerialPortManager.mRequest.Append(ByteArrayConverter.toString(e.mData).Replace("-", ""));
}
...
}
The communication should be like below:
request: 5555555555555555808080800100000001001A0006070001060031B1
response: 55555555555555558080808001000000010000808076
request: 5555555555555555808080800200000001001A0006070001060034B2
response: 555555555555555580808080020000000100008041BA
request: 5555555555555555808080800300000001001A000607000106003473
response: 55555555555555558080808003000000010000804049
And so on. It is just example, what the request frame should look like. As you can see, the device asks for 1,2,3,4, etc. It always asks in this order. The last four values are just checksum. What I receive after response is like:
request: 5555555555555555808080800200000001001A0006070001060034B2
response: 555555555555555580808080020000000100008041BA
request: 55555555555555558080808002000000000A0100000000000000BCAE
After response for 2, there should be an ask for 3. If I set the software to not responding, every request looks fine.
What I am doing wrong?
Ok, so everything is okay. My COM interface is broken :( Everything is fine with both ways - DataReceived event handler and read() right after write() (no matter which solution is better in programming way). Thank you all for trying help with my case anyway!

An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in System.dll

So I have searched a lot of areas for this answer and I am confused on what this error is doing. Whenever I press the start server button...
...I get this error "An unhandled exception of type 'System.Net.Sockets.SocketException' occurred in System.dll"
My code is quite long but I have no clue what to do...
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
private bool isserver = false;
public const int MAXSIZE = 10;
public Form1()
{
InitializeComponent();
clearoutput();
}
TcpListener tcpl = new TcpListener(IPAddress.Parse(getip()), 2546);
List<TcpClient> clients = new List<TcpClient>();
List<string> names = new List<string>();
bool CommandMode = false;
List<string> banlist = new List<string>();
TcpClient Client = new TcpClient();
//client setup
private void button1_Click(object sender, EventArgs e)
{
try {
Output.Text = Output.Text + "You have joined as a client";
Client = new TcpClient();
Client.Connect(IP_address.Text, 2546);
Thread myThread = new Thread(new ParameterizedThreadStart(Listen));
myThread.Start(Client);
//whenever you send a message you must include the next two lines
//Client.GetStream().Write(new byte[] { (byte)Encoding.Unicode.GetByteCount(name + " has joined") }, 0, 1);
//Client.GetStream().Write(Encoding.Unicode.GetBytes(name + " has joined"), 0, Encoding.Unicode.GetByteCount(name + " has joined"));
//the two lines above
Client.GetStream().Write(new byte[] { (byte)Encoding.Unicode.GetByteCount("\\join" + getip()) }, 0, 1);
Client.GetStream().Write(Encoding.Unicode.GetBytes("\\join" + getip()), 0, Encoding.Unicode.GetByteCount("\\join" + getip()));
}
catch { }
IP_address.Visible = false;
Join_btn.Visible = false;
Start_btn.Visible = false;
Output.Visible = true;
Input.Visible = true;
text1.Visible = true;
text1.Visible = true;
}
private void clearoutput()
{
Output.Text = "";
}
//server setup---
private void Start_btn_Click(object sender, EventArgs e)
{
isserver = true;
server_IP_lbl.Text = $"Since you are a server:\nYour ip address is : "+getip();
//if You need a new banlist make sure you click here and allow this
Write_to_output("you are a server");
try
{
StreamReader readerfrban = new StreamReader("banlist");
readerfrban.Close();
Write_to_output("we found a banlist \n no worries");
}
catch
{
Write_to_output("Error- could not find a banlist creating one now");
StreamWriter banlistmaker = new StreamWriter("banlist");
banlistmaker.Close();
}
//open banlist
StreamReader readerforban = new StreamReader("banlist");
string reader = "";
//read all bans in
do
{
reader = readerforban.ReadLine();
if (reader != null)
banlist.Add(reader);
} while (reader != null);
tcpl.Start();
//Thread AcceptSocketsThread = new Thread(AcceptSockets);
//AcceptSocketsThread.Start();
/* while (true)
{
string Message = Console.ReadLine();
if (Message.StartsWith("\\Kick"))
{
Console.Clear();
CommandMode = true;
int clientID = 0;
foreach (TcpClient client in clients)
{
Write_to_output(clientID.ToString() + ") " + names[clientID] + " " + client.Client.RemoteEndPoint);
clientID++;
}
Write_to_output("\n\n Enter the number of the person you want to kick");
TcpClient toRemove = clients[Convert.ToInt32(Console.ReadLine())];
toRemove.Close();
clients.Remove(toRemove);
CommandMode = false;
}
else if (Message.StartsWith("\\Reset"))
{
foreach (TcpClient client in clients)
{
client.Close();
}
clients.Clear();
Write_to_output("KICKED EVERY BODY");
}
else if (Message.StartsWith("\\ban"))
{
Console.Clear();
CommandMode = true;
int clientID = 0;
foreach (TcpClient client in clients)
{
Write_to_output(clientID.ToString() + ") " + names[clientID] + " " + client.Client.RemoteEndPoint);
clientID++;
}
Write_to_output("\n\n Enter the number of the person you want to kick and ban");
TcpClient toRemove = clients[Convert.ToInt32(Console.ReadLine())];
banlist.Add(toRemove.Client.RemoteEndPoint.ToString().Split(new char[] { ':' })[0]);
toRemove.Close();
clients.Remove(toRemove);
CommandMode = false;
}
//starts game
else
{
foreach (TcpClient client in clients)
{
SendMessage(Message, client);
}
}
}*/
IP_address.Visible = false;
Join_btn.Visible = false;
Start_btn.Visible = false;
Output.Visible = true;
Input.Visible = true;
text1.Visible = true;
text1.Visible = true;
}
void SendMessage(string message, TcpClient reciever)
{
try {
reciever.GetStream().Write(new byte[] { (byte)Encoding.Unicode.GetByteCount(message) }, 0, 1);
reciever.GetStream().Write(Encoding.Unicode.GetBytes(message), 0, Encoding.Unicode.GetByteCount(message));
}
catch
{
Write_to_output("Was unable to send to any users error code 1.0.0.0");
}
}
void AcceptSockets()
{
while (true)
{
TcpClient client = tcpl.AcceptTcpClient();
Thread myThread = new Thread(new ParameterizedThreadStart(Listen));
clients.Add(client);
myThread.Start(client);
}
}
void setname(string name)
{
names.Add(name);
}
void Listen(object obj)
{
TcpClient TCPClient = (TcpClient)obj;
while (true)
{
try
{
byte[] fBuffer = new byte[1];
TCPClient.GetStream().Read(fBuffer, 0, 1);
byte[] buffer = new byte[(int)fBuffer[0]];
TCPClient.GetStream().Read(buffer, 0, (int)fBuffer[0]);
string message = Encoding.Unicode.GetString(buffer).Trim();
if (message.StartsWith("\\join"))
{
message = message.Remove(0, 5);
int a = 0;
for (int i = 0; i < banlist.Count; i++)
{
if (message.StartsWith(banlist[i]))
{
a = 1;
}
}
if (a == 0)
{
//int namespaceer = 0;
//foreach (char chars in message)
//{
// namespaceer += 1;
// if (chars == '+')
// break;
//}
// message = message.Remove(0, namespaceer);
}
else
{
//Write_to_output("Person on banlist");
// TcpClient toRemove = clients[Convert.ToInt32(Console.ReadLine())];
//toRemove.Close();
}
}
else
{
foreach (TcpClient client in clients)
{
if (client != TCPClient)
{
SendMessage(message, client);
}
}
if (!CommandMode)
{
Write_to_output(message.Trim());
}
else
{
}
}
}
catch (Exception e)
{
Write_to_output(e.ToString());
}
}
}
static string getip()
{
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily.ToString() == "InterNetwork")
{
localIP = ip.ToString();
}
}
return localIP;
}
public void Write_to_output(string towrite)
{
//check outputs length
int numLines = 0;
string text = Output.Text;
numLines = Text.Split('\n').Length;
if (numLines == MAXSIZE)
{
Output.Text = towrite;
}
else
{
Output.Text = Output.Text + $"\n" + towrite;
}
}
private void Input_Leave(object sender, EventArgs e)
{
string message = Input.Text;
if (isserver == false)
{
//send client code
SendMessage(message,Client);
}
else
{
//send server code
foreach (TcpClient client in clients)
{
SendMessage(message, client);
}
}
}
}
}
Please help me...
Check if the port TCP 2546 is not busy by another process or code instance on the listening machine.
Or choose another free port to listen to.

Categories

Resources