Socket Exception on a console application - c#

I was trying to create an application to create a bound between two clients(two form application) to transmit through TCP protocol some data. I wrote the applicatin in C# using System.Net.Sockets (I am a beginner in System.Net) and I get this error:
System.Net.Sockets.SocketException (0x80004005): A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 192.168.2.101:100 at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.Sockets.Socket.Connect(EndPoint remoteEP) at System.Net.Sockets.Socket.Connect(IPAddress address, Int32 port) at Client_003.Form1.LoopConnect()
I must say that this went well on my machine and another one that is bound with mine by router.
This is the code for server:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Server_003
{
class Program
{
private static List<Socket> _clientSockets = new List<Socket>();
private static List<string> _numeClient = new List<string>();
private static List<int> _indexPartener = new List<int>();
private static byte[] _buffer = new byte[10000];
private static Socket _serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
static void Main(string[] args)
{
SetUpServer();
Console.ReadLine();
}
private static void SetUpServer()
{
//byte[] test = Encoding.ASCII.GetBytes("lose partener");
//Console.WriteLine(test.Length);
Console.WriteLine("Seting up server ... ");
_serverSocket.Bind(new IPEndPoint(IPAddress.Parse("192.168.2.101"), 100));
_serverSocket.Listen(5);
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallBack), null);
}
private static string GetNume()
{
int index = 0;
if (_numeClient.Count == 0)
return "Client 0";
else
for (int i = 0; i < _numeClient.Count; i++)
if (_numeClient[i] != "Client " + index.ToString())
return "Client " + index.ToString();
else
index++;
return "Client " + index.ToString();
}
private static void AcceptCallBack(IAsyncResult AR)
{
Socket socket = _serverSocket.EndAccept(AR); //return client socket
_clientSockets.Add(socket);
_indexPartener.Add(-1);
_numeClient.Add(GetNume());
Console.WriteLine("Client conected with IP: " + socket.RemoteEndPoint);
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket);
_serverSocket.BeginAccept(new AsyncCallback(AcceptCallBack), null); //permitem sa mai accepte clienti
}
private static string GetNumeClienti()
{
string clienti = "";
for (int i = 0; i < _numeClient.Count; i++)
if(_indexPartener[i] == -1)
clienti += i.ToString() + " " + _numeClient[i] + "\r\n";
return clienti;
}
private static string GetClientiPlusParteneri()
{
string clienti = "";
for (int i = 0; i < _numeClient.Count; i++)
if (_indexPartener[i] == -1)
clienti += _numeClient[i] + " Null\r\n";
else
clienti += _numeClient[i] + " " + _numeClient[_indexPartener[i]] + "\r\n";
return clienti;
}
private static void ReceiveCallBack(IAsyncResult AR)
{
Socket socket = (Socket)AR.AsyncState;
int index = _clientSockets.IndexOf(socket);
int receive = socket.EndReceive(AR);
byte[] DataBuffReceive = new byte[receive];
if (receive == 13)
_indexPartener[index] = -1;
else
if (_indexPartener[index] == -1)
{
Array.Copy(_buffer, DataBuffReceive, receive);
string text = Encoding.ASCII.GetString(DataBuffReceive);
string raspuns = "Invalid request!";
if (text.ToLower() == "get time")
{
raspuns = DateTime.Now.ToLongTimeString();
}
if (text.IndexOf(' ') > 0 && text.Substring(0, text.IndexOf(' ')) == "NuMe")
{
_numeClient[index] = text.Substring(text.IndexOf(' ') + 1);
raspuns = "Nume setat la " + _numeClient[index];
}
if (text.ToLower() == "get clienti liberi")
raspuns = GetNumeClienti();
if (text.ToLower() == "get clienti si parteneri")
raspuns = GetClientiPlusParteneri();
if (text.ToLower() == "e--")
{
raspuns = "Deconectat!";
_clientSockets.RemoveAt(index);
_numeClient.RemoveAt(index);
_indexPartener.RemoveAt(index);
return;
}
byte[] DataBuffSend = Encoding.ASCII.GetBytes(raspuns);
socket.BeginSend(DataBuffSend, 0, DataBuffSend.Length, SocketFlags.None, new AsyncCallback(SendCallBack), socket);
}
else
_clientSockets[index].BeginSend(DataBuffReceive, 0, DataBuffReceive.Length, SocketFlags.None, new AsyncCallback(SendCallBack), _clientSockets[index]);
socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallBack), socket);
}
private static void SendCallBack(IAsyncResult AR)
{
Socket socket = (Socket)AR.AsyncState;
socket.EndSend(AR);
}
}
}
And this is the code for client(a form application):
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
namespace Client_003
{
public partial class Form1 : Form
{
private byte[] _buffer = new byte[10000];
private Socket _clientSoket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
private bool continuare = true;
public Form1()
{
InitializeComponent();
groupBox1.Text = "";
groupBox1.Visible = false;
}
private void LoopConnect()
{
if (_clientSoket.Connected)
MessageBox.Show("It's connected!");
else
{
while (!_clientSoket.Connected)
{
try
{
MessageBox.Show("Trying to connect!");
_clientSoket.Connect(IPAddress.Parse("192.168.2.101"), 100);
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
}
textBox2.Clear();
textBox2.Text = "Connected!";
groupBox1.Visible = true;
}
private void primire()
{
if (continuare)
{
int rec = _clientSoket.Receive(_buffer);
byte[] data = new byte[rec];
Array.Copy(_buffer, data, rec);
string text = Encoding.ASCII.GetString(data);
if (text.IndexOf(' ') > 0 && text.ToLower().Substring(0, text.IndexOf(' ')) == "acceptare_partener")
{
DialogResult raspuns = MessageBox.Show("Acceptati ca partener pe " + text.Substring(text.IndexOf(' ') + 1), "Acceptare partener", MessageBoxButtons.YesNo);
if (raspuns == DialogResult.Yes)
{
byte[] cerere = Encoding.ASCII.GetBytes("yes");
_clientSoket.Send(cerere);
primire(); // expected confirmation
}
else
{
byte[] cerere = Encoding.ASCII.GetBytes("no");
_clientSoket.Send(cerere);
primire(); // expected confirmation
}
}
textBox2.Text += "\r\n" + text;
}
}
private void button1_Click(object sender, EventArgs e)
{
LoopConnect();
}
private void button2_Click(object sender, EventArgs e)
{
byte[] cerere = Encoding.ASCII.GetBytes(textBox1.Text);
_clientSoket.Send(cerere);
textBox1.Clear();
primire();
}
private void button3_Click(object sender, EventArgs e)
{
this.Close();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (_clientSoket.Connected)
{
continuare = false;
byte[] cerere = Encoding.ASCII.GetBytes("e--");
_clientSoket.Send(cerere);
_clientSoket.Close();
}
}
}
}

Related

How can I close the udp connection properly without throwing the "Unable to access disposed object" exception?

I need to close udp client connection without getting error says: "Cannot access object disposed" that is an exception.
This is
RehearsalStart.cs
using System;
using System.Collections;
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.Net.Sockets;
using System.Net;
using System.Net.NetworkInformation;
using EntitiesLayer;
using BusinessLogicLayer;
using System.Data.SqlClient;
namespace PresentationLayer
{
public partial class RehearsalStart : Form
{
IPEndPoint Broadcast; //IP address endpoint representing a broadcast
IPEndPoint Any; //IP address endpoint representing any address
IPEndPoint PIC; //IP address endpoint representing the PIC we are connected to
IPEndPoint Origin; // IP address endpoint representing the source of the input data
bool Connected; //Indicates if there is a connection with any PIC
byte[] codQuestion = { (byte)'P', (byte)'C' }; //Array of bytes that is broadcast as a search code
UdpClient SocketALL; //PC socket in UDP
//Delegates used
public delegate void AsyncCallback(IAsyncResult ar);
public delegate void AddList(string o);
public string type;
public string name;
public string surname;
//Constructor
public RehearsalStart(string Type, string Name, string Surname)
{
type = Type;
name = Name;
surname = Surname;
InitializeComponent();
label1.Text = type + ": " + name + " " + surname;
}
private void RehearsalStart_Load(object sender, EventArgs e)
{
Connected = false;
try
{
SocketALL = new UdpClient();
Broadcast = new IPEndPoint(IPAddress.Broadcast, 30303);
Any = new IPEndPoint(IPAddress.Any, 30303);
SocketALL.Client.Bind(Any);
SocketALL.BeginReceive(ReceiveBrodcast, SocketALL);
SocketALL.Send(codQuestion, codQuestion.Length, Broadcast);
} catch (Exception ex){
throw ex;
}
public void ReceiveBrodcast(IAsyncResult ar)
{
string MAC = NetworkInterface.GetAllNetworkInterfaces()[0].GetPhysicalAddress().ToString();
MAC = MAC[0].ToString() + MAC[1].ToString() + "-" + MAC[2].ToString() + MAC[3].ToString() + "-" + MAC[4].ToString() + MAC[5].ToString() + "-" + MAC[6].ToString() + MAC[7].ToString() + "-" + MAC[8].ToString() + MAC[9].ToString() + "-" + MAC[10].ToString() + MAC[11].ToString();
UdpClient MyUDP = (UdpClient)ar.AsyncState;
string Data = Convert(MyUDP.EndReceive(ar, ref Origin));
MyUDP.BeginReceive(ReceiveBrodcast, MyUDP);
switch (Data)
{
case "PC":
SocketALL.Send(Convert(name_textBox.Text + "\r\n" + MAC), name_textBox.Text.Length + 2 + MAC.Length, Broadcast);
break;
default:
Data = Origin.Address.ToString() + "\n" + Data.Replace("\r\n", "\n");
disp_listView.Invoke(new AddList(AddDisp), Data);
break;
}
}
public void AddDisp(string o)
{
for (int n = 0; n < disp_listView.Items.Count; n++)
{
if (disp_listView.Items[n].SubItems[0].Text == (o.Split('\n'))[0])
{
return;
}
}
disp_listView.Items.Add(new ListViewItem(o.Split('\n')));
}
private void Search_button_Click(object sender, EventArgs e)
{
disp_listView.Items.Clear();
try
{
SocketALL.Send(codQuestion, codQuestion.Length, Broadcast);
}
catch (Exception ex)
{
throw ex;
}
}
string Convert(byte[] a)
{
return Encoding.ASCII.GetString(a);
}
byte[] Convert(string a)
{
return Encoding.ASCII.GetBytes(a);
}
private void disp_listView_SelectedIndexChanged(object sender, EventArgs e)
{
if (!Connected && disp_listView.SelectedItems.Count != 0 && disp_listView.SelectedItems[0].SubItems[1].Text[0] == 'A')
{
button4.Enabled = false;
button3.Enabled = true;
}
else
{
button4.Enabled = false;
button3.Enabled = false;
}
}
private void button3_Click(object sender, EventArgs e)
{
PIC = new IPEndPoint(IPAddress.Parse(disp_listView.SelectedItems[0].SubItems[0].Text), 3000);
button4.Enabled = true;
button3.Enabled = false;
Connected = true;
disp_listView.Enabled = false;
Main Win = new Main(type, name, surname, number, PIC);
Win.ShowDialog();
button4.Enabled = false;
button3.Enabled = true;
Connected = false;
disp_listView.Enabled = true;
Close();
}
private void button4_Click(object sender, EventArgs e)
{
button4.Enabled = false;
button3.Enabled = true;
Connected = false;
disp_listView.Enabled = true;
System.Windows.Forms.Application.Exit();
}
}
And Main.cs
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.Net.Sockets;
using System.Net;
using System.Net.NetworkInformation;
using EntitiesLayer;
using BusinessLogicLayer;
using System.Data.SqlClient;
namespace PresentationLayer
{
public partial class Main : Form
{
string type;
string name;
string surname;
//Members
int packs = 0;
UdpClient SocketPIC;
IPEndPoint Origin;
public delegate void AsyncCallback(IAsyncResult ar);
public delegate void Values(byte[] bytes);
//Methods
public Main()
{
InitializeComponent();
}
public Main(string Type, string Name, string Surname, int Number, IPEndPointP)
{
type = Type;
name = Name;
surname = Surname;
InitializeComponent();
SocketPIC = new UdpClient(3000);
SocketPIC.Connect(P);
SocketPIC.BeginReceive(ReceiveFrame, SocketPIC);
packs_timer.Enabled = true;
}
private void packs_timer_Tick(object sender, EventArgs e)
{
packs = 0;
SocketPIC.Send(new byte[] { 101, 0, 0, 0, 0 }, 5);
}
public void ReceiveFrame(IAsyncResult ar)
{
UdpClient MyUDP = (UdpClient)ar.AsyncState;
if (MyUDP.Client != null)
{
byte[] Data = MyUDP.EndReceive(ar, ref Origin);
MyUDP.BeginReceive(ReceiveFrame, MyUDP);
this.Invoke(new Values(AddData), Data);
}
}
private void CloseFrame(IAsyncResult ar)
{
UdpClient MyUDP = (UdpClient)ar.AsyncState;
try
{
if (MyUDP.Client != null) //ERROR
{
MyUDP.EndReceive(ar, ref Origin); //ERROR
MyUDP.Close(); //ERROR
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (SocketPIC.Client != null)
{
SocketPIC.EndReceive(ar, ref Origin);
SocketPIC.Close();
}
}
}
public void AddData(byte[] data)
{
if (data[0] == 102 && packs < 5)
{
for (int n = 1; n < data.Length; n += 12)
{
MEASURE.Add_I1(data[n], data[n + 1]);
MEASURE.Add_V1(data[n + 2], data[n + 3]);
MEASURE.Add_I2(data[n + 4], data[n + 5]);
MEASURE.Add_V2(data[n + 6], data[n + 7]);
MEASURE.Add_I3(data[n + 8], data[n + 9]);
MEASURE.Add_V3(data[n + 10], data[n + 11]);
}
packs++;
}
else
{
SocketPIC.Send(new byte[] { 102, 0, 0, 0, 0 }, 5);
//ADDING DATA
}
private void button_state_Click(object sender, EventArgs e)
{
if (button_state.Text == "Pause")
{
button_state.Text = "Continue";
packs_timer.Enabled = false;
}
else
{
button_state.Text = "Pause";
packs_timer.Enabled = true;
}
}
private void file_data_U_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
packs_timer.Enabled = false;
SocketPIC.Send(new byte[] { 102, 0, 0, 0, 0 }, 5);
SocketPIC.BeginReceive(CloseFrame, SocketPIC); //HERE is the error
RehearsalStart screen = new Rehearsal(type, name, surname);
screen.Show();
Close();
/*
packs_timer.Enabled = false;
SocketPIC.Send(new byte[] { 102, 0, 0, 0, 0 }, 5);
SocketPIC.Close();
Close();
*/
}
}
}
How may I fix this issue? I need to close udp client connection every time I disconnect and connect when I'm navigating between RehearsalStart and Main forms.
I'm working with an electronic board in c#.

When I am multithreading I am only able to send message from the first thread once after that I am unable to send message from the first thread

I am working on a chat application which is multi-client in nature with a single server but I am facing an issue. When I connect a single client to the serve everything works perfectly but later when I connect 2 or more clients then I am only able to send one single messages from the first client and then the server stops receiving messages from the first client while I can still smoothly send messages from the second client without any issues
Below is my server code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Server
{
public partial class Form1 : Form
{
delegate void SetTextCallback(string text);
TcpListener listener;
TcpClient client;
NetworkStream ns;
Thread t;
Thread main;
string[] client_name = new string[50];
int count;
int count1 = 0;
int indice = 0;
public Form1()
{
InitializeComponent();
button2.Enabled = false;
main = new Thread(runserver);
}
public void runserver()
{
listener = new TcpListener(IPAddress.Loopback, 8888);
listener.Start();
while (true)
{
client = listener.AcceptTcpClient();
ns = client.GetStream();
//t = new Thread(connector);
var childSocketThread = new Thread(() =>
{
connector();
});
childSocketThread.Start();
//t.Start();
}
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
main.Start();
button2.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
button3.Enabled = false;
String s = "Close";
byte[] byteTime = Encoding.ASCII.GetBytes(s);
ns.Write(byteTime, 0, byteTime.Length);
client.GetStream().Close();
client.Close();
listener.Stop();
button2.Enabled = false;
button1.Enabled = true;
textBox1.Text += "Server closed";
}
private void button3_Click(object sender, EventArgs e)
{
String s = textBox2.Text;
textBox1.Text += "Server >> " + textBox2.Text + "\r\n";
byte[] byteTime = Encoding.ASCII.GetBytes(s);
ns.Write(byteTime, 0, byteTime.Length);
}
public void connector()
{
byte[] bytes = new byte[1024];
while (true)
{
int bytesRead = ns.Read(bytes, 0, bytes.Length);
string statement = Encoding.ASCII.GetString(bytes, 0, bytesRead);
string temp = "";
if (statement[0] == '#')
{
count++;
while (statement[count] != '#')
{
temp += statement[count];
count++;
}
client_name[indice] = temp;
indice++;
statement = statement.Remove(0, temp.Length+2);
this.text1(statement);
count = 0;
}
else
this.text1(statement);
}
}
private void text1(string text)
{
int count2 = 1;
string str = "";
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(text1);
this.Invoke(d, new object[] { text });
}
else
{
if(text[0] == '*')
{
while (text[count2] != '*')
{
str += text[count2];
count2++;
}
text = text.Remove(0, str.Length + 2);
this.textBox1.Text += str + " >> " + text + "\r\n";
}
else
this.textBox1.Text += client_name[indice - 1] + " >> " + text + "\r\n";
}
}
And here is my client code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Client
{
public partial class Form1 : Form
{
delegate void SetTextCallback(string text);
TcpClient client;
NetworkStream ns;
Thread t = null;
string client_name;
int port_num = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
client_name = textBox4.Text;
}
private void button2_Click(object sender, EventArgs e)
{
button2.Enabled = false;
client = new TcpClient(textBox1.Text, port_num);
ns = client.GetStream();
String s = "#" + client_name + "#" +" Connected";
byte[] byteTime = Encoding.ASCII.GetBytes(s);
ns.Write(byteTime, 0, byteTime.Length);
t = new Thread(Connector);
t.Start();
}
private void button3_Click(object sender, EventArgs e)
{
String s = "*" + client_name + "*" + textBox3.Text;
textBox2.Text += client_name +" >> " + textBox3.Text + "\r\n";
byte[] byteTime = Encoding.ASCII.GetBytes(s);
ns.Write(byteTime, 0, byteTime.Length);
}
public void Connector()
{
byte[] bytes = new byte[1024];
while (true)
{
int bytesRead = ns.Read(bytes, 0, bytes.Length);
string data = Encoding.ASCII.GetString(bytes, 0, bytesRead);
if (data == "Close")
{
button3.Enabled = false;
t.Abort();
client.GetStream().Close();
client.Close();
}
else
this.Text1(data);
}
}
private void Text1(string text)
{
if (this.textBox2.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(Text1);
this.Invoke(d, new object[] { text });
}
else
{
this.textBox2.Text = this.textBox2.Text + "Server >> " + text + "\r\n";
}
}
private void button4_Click(object sender, EventArgs e)
{
string temp = textBox5.Text;
port_num = int.Parse(temp);
}
}
}
Kindly help me out with this also I am new with socket programming
TcpClient and NetworkStream in server code should be keeped in a list for futher use. Like blow server code
public partial class Form1 : Form
{
delegate void SetTextCallback(string text);
TcpListener listener;
List<TcpClient> clients = new List<TcpClient>();
List<NetworkStream> ns = new List<NetworkStream>();
Thread t;
Thread main;
string[] client_name = new string[50];
int count;
int count1 = 0;
int indice = 0;
public Form1()
{
InitializeComponent();
button2.Enabled = false;
main = new Thread(runserver);
}
public void runserver()
{
listener = new TcpListener(IPAddress.Loopback, 8888);
listener.Start();
while (true)
{
TcpClient tmpClient = listener.AcceptTcpClient();
clients.Add(tmpClient);
ns.Add(tmpClient.GetStream());
//t = new Thread(connector);
var childSocketThread = new Thread(() =>
{
connector(ns.Count - 1);
});
childSocketThread.Start();
//t.Start();
}
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
main.Start();
button2.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
button3.Enabled = false;
String s = "Close";
byte[] byteTime = Encoding.ASCII.GetBytes(s);
for(int i = 0; i < ns.Count; i++)
{
ns[i].Write(byteTime, 0, byteTime.Length);
clients[i].GetStream().Close();
clients[i].Close();
}
listener.Stop();
button2.Enabled = false;
button1.Enabled = true;
textBox1.Text += "Server closed";
ns.Clear();
clients.Clear();
}
private void button3_Click(object sender, EventArgs e)
{
String s = textBox2.Text;
textBox1.Text += "Server >> " + textBox2.Text + "\r\n";
byte[] byteTime = Encoding.ASCII.GetBytes(s);
ns.ForEach(item => { item.Write(byteTime, 0, byteTime.Length); });
//ns.Write(byteTime, 0, byteTime.Length);
}
public void connector(int index)
{
byte[] bytes = new byte[1024];
while (true)
{
int bytesRead = ns[index].Read(bytes, 0, bytes.Length);
string statement = Encoding.ASCII.GetString(bytes, 0, bytesRead);
string temp = "";
if (statement[0] == '#')
{
count++;
while (statement[count] != '#')
{
temp += statement[count];
count++;
}
client_name[indice] = temp;
indice++;
statement = statement.Remove(0, temp.Length + 2);
this.text1(statement);
count = 0;
}
else
this.text1(statement);
}
}
private void text1(string text)
{
int count2 = 1;
string str = "";
if (this.textBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(text1);
this.Invoke(d, new object[] { text });
}
else
{
if (text[0] == '*')
{
while (text[count2] != '*')
{
str += text[count2];
count2++;
}
text = text.Remove(0, str.Length + 2);
this.textBox1.Text += str + " >> " + text + "\r\n";
}
else
this.textBox1.Text += client_name[indice - 1] + " >> " + text + "\r\n";
}
}
}

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);
}

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