I have read through articles about connection using socket. I'm trying to stay connected to the server and send message to the server. I did the below, I send the message content to the server, after 4 times sent I get the following error and can not send again.
System.Net.Sockets.SocketException: 'An established connection was aborted by the software in your host machine'
This is my snipped code
private static IPEndPoint IPendPoint = new IPEndPoint(IPAddress.Parse("10.10.10.123"), 6666);
private static Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
private static byte[] buffer = new byte[1024];
private void bt_conn_Click(object sender, EventArgs e)
{
try
{
socket.Connect(IPendPoint);
}
catch
{
MessageBox.Show("Can not connect to server");
}
}
private void bt_disconn_Click(object sender, EventArgs e)
{
socket.Close();
//socket.Disconnect(true);
//socket.Shutdown(SocketShutdown.Both);
//socket.Dispose();
}
private void bt_send_Click(object sender, EventArgs e)
{
socket.Send(Encoding.ASCII.GetBytes(txt_msg.Text));
listBox1.Items.Add("Sent to server: " + txt_msg.Text + "\r\n");
buffer = new byte[1024];
int rec = socket.Receive(buffer, 0, buffer.Length, 0);
Array.Resize(ref buffer, rec);
listBox1.Items.Add("Receive from server: " + Encoding.ASCII.GetString(buffer) + "\r\n");
}
Probably I missing something else, get make me wrong. So, let me know if I'm incorrect some code. I find some code like. This will turn on keep-alive, but the default 2 hour threshold will be used! . Anyways to keep through the application running.
TcpClient client = new TcpClient();
client.Client.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.KeepAlive, true);