Error in Working with Socket When Sending Object Frequently - c#

I'm writing a program that can manage computers in a network environment.
I try to be a part of this program will assign the control of the remote client(Remote Desktop) . but my target is like teamviewer not RDC(RDP) .
i want make a service and put it into Client , that Service running every time (Automatic , Auto Start)
I use sending mouse and keyboard from server to client and screenshot of desktop of client will be transfer to server, the destination computer must control.
i write it by BackgroundWorker in loop ( in Complete_BW i put BW.RunWorkerAsync() )
i use socket and when i run program my server rise error after 1 or 2 times sent desktop image to server , error is in Socket.EndPoint ...
codes is here :
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;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.IO;
namespace remServer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
bw.RunWorkerAsync();
}
public Image GetImage(byte[] byteArrayIn)
{
Image ret = null;
try
{
MemoryStream ms = new MemoryStream(byteArrayIn);
ret = Image.FromStream(ms);
}
catch { }
return ret;
}
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
FTServerCode f = new FTServerCode();
Byte[] getCap = f.StartServer();
img.Image = GetImage(getCap);
}
private void bw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
bw.RunWorkerAsync();
}
}
public class FTServerCode
{
IPEndPoint ipEnd;
Socket sock;
public FTServerCode()
{
try
{
ipEnd = new IPEndPoint(IPAddress.Any, 5656); // Error In this Line
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
sock.Bind(ipEnd);
}
catch { }
}
public Byte[] StartServer()
{
byte[] clientData = new byte[1024 * 5000];
try
{
sock.Listen(100);
Socket clientSock = sock.Accept();
int receivedBytesLen = clientSock.Receive(clientData);
clientSock.Close();
}
catch (Exception ex)
{
MessageBox.Show("File Receving error." + ex.Message);
}
return clientData;
}
}
}
if client code is Necessary tell me to put in here . tnx

Related

my socket application doesnt connect when i try it on the internet

im programming a socket application using c# (.net framework) but when i try it on the local system or private network it works well but when i try it on two different system using internet (public network) it never connect
its my code:
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;
using System.Net.Sockets;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
SocketPermission me = new SocketPermission(NetworkAccess.Accept, TransportType.Tcp, "", SocketPermission.AllPorts);
Socket mes =
new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
Socket des;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
try
{
IPHostEntry iphost = Dns.GetHostEntry("");
IPAddress ipaddr = iphost.AddressList[0];
MessageBox.Show(ipaddr.ToString());
IPEndPoint iep = new IPEndPoint(ipaddr, 44444);
label1.Text = ipaddr.ToString();
mes.Bind(iep);
mes.Listen(4);
des = mes.Accept();
MessageBox.Show("connected");
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
IPHostEntry iphost = Dns.GetHostEntry("");
IPAddress ipaddr = iphost.AddressList[0];
MessageBox.Show(ipaddr.ToString());
IPEndPoint iep = new IPEndPoint(IPAddress.Parse(textBox1.Text), 44444);
mes.Connect(iep);
}
catch (Exception err)
{
MessageBox.Show(err.ToString());
}
}
}
}
textbox1 return server ipv6.
im using socket permission to open all ports for tcp .
and ipv6 because its unique .

How can I make a server print a notification as soon as a client connects to it?

Take a look at the following two programs:
//Server
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.Tasks;
namespace MyServerProgram
{
class Program
{
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
int port = 2000;
TcpListener listener = new TcpListener(ip, port);
listener.Start();
TcpClient client = listener.AcceptTcpClient();
NetworkStream netStream = client.GetStream();
BinaryReader br = new BinaryReader(netStream);
try
{
while (client.Client.Connected)
{
string str = br.ReadString();
Console.WriteLine(str);
}
}
catch
{
br.Close();
netStream.Close();
client.Close();
listener.Stop();
}
}
}
}
//Client
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.Tasks;
namespace MyClientProgram
{
class Program
{
static void Main(string[] args)
{
int port = 2000;
TcpClient client = new TcpClient("localhost", port);
NetworkStream netStream = client.GetStream();
BinaryWriter br = new BinaryWriter(netStream);
try
{
int i=1;
while (client.Client.Connected)
{
br.Write(i.ToString());
br.Flush();
i++;
int milliseconds = 2000;
System.Threading.Thread.Sleep(milliseconds);
}
}
catch
{
br.Close();
netStream.Close();
client.Close();
}
}
}
}
These programs are working fine.
Suppose, at this point of this program, I need the server to print a message on the screen as soon as a client gets connected to it, and, also when the client is disconnected.
How can I do that?
AcceptTcpClient blocks execution and starts waiting for connection. So right after it you can write message that client connected. Also you could write connected client address. Just for information, but sometimes it could be helpful.
TcpClient client = listener.AcceptTcpClient();
ShowMessage("Connected " + ((IPEndPoint)client.Client.RemoteEndPoint).Address);
For detect client disconnect you could catch exceptions. Change your catch like this:
catch (Exception ex) {
var inner = ex.InnerException as SocketException;
if (inner != null && inner.SocketErrorCode == SocketError.ConnectionReset)
ShowMessage("Disconnected");
else
ShowMessage(ex.Message);
...

c# TCP IP client and server no respond error

i have a simple TCP/IP client and server that does not work:
i want to use it to transfer data between some clients and a server
enter image description here
enter image description here
on server side i have:
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;
using System.Collections;
namespace TCP_IP_Server
{
public partial class frmMain : Form
{
private ArrayList nSockets;
public frmMain()
{
InitializeComponent();
}
private void frmMain_Load(object sender, EventArgs e)
{
IPHostEntry IPhost = Dns.GetHostByName(Dns.GetHostName());
lblStatus.Text = "IP Address: " + IPhost.AddressList[0].ToString();
nSockets = new ArrayList();
Thread thdListner = new Thread(new ThreadStart(listnerThread));
}
public void listnerThread()
{
TcpListener tcpListener = new TcpListener(8080);
tcpListener.Start();
while(true)
{
Socket handlerSocket = tcpListener.AcceptSocket();
if(handlerSocket.Connected)
{
Control.CheckForIllegalCrossThreadCalls = false;
lbConnections.Items.Add(handlerSocket.RemoteEndPoint.ToString() + " Connected.");
lock (this)
{
nSockets.Add(handlerSocket);
}
ThreadStart thdstHandler = new ThreadStart(handlerThread);
Thread thdHnadler = new Thread(thdstHandler);
thdHnadler.Start();
}
}
}
public void handlerThread()
{
Socket handlerSocket = (Socket)nSockets[nSockets.Count - 1];
NetworkStream networkStream = new NetworkStream(handlerSocket);
int thisRead = 0;
int BlockSize = 1024;
byte[] dataByte = new byte[BlockSize];
lock (this)
{
Stream fileStream = File.OpenWrite(#"%userprofile%\desktop\SubmitedFile.txt");
while(true)
{
thisRead = networkStream.Read(dataByte, 0, BlockSize);
fileStream.Write(dataByte, 0, thisRead);
if (thisRead == 0)
break;
}
fileStream.Close();
}
lbConnections.Items.Add("File Written.");
handlerSocket = null;
}
}
}
and on Clinet side:
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 TCP_IP_Client
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
}
private void btnBrowse_Click(object sender, EventArgs e)
{
ofdBrowse.ShowDialog();
txtFile.Text = ofdBrowse.FileName;
}
private void btnSend_Click(object sender, EventArgs e)
{
Stream fileStream = File.OpenRead(txtFile.Text);
byte[] fileBuffer = new byte[fileStream.Length];
fileStream.Read(fileBuffer, 0, (int)fileStream.Length);
TcpClient tcp = new TcpClient(txtServer.Text, 8080);
NetworkStream networkStream = tcp.GetStream();
networkStream.Write(fileBuffer, 0, fileBuffer.GetLength(0));
networkStream.Close();
}
}
}
i am running the server on a VPS that hase statick IP adress and the client on my own pc, but after hiting send button an exception occures:
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 **.**.**.**:8080
1. Programmatic Issue
Don't forget to start the thread after creating
private void frmMain_Load(object sender, EventArgs e)
{
IPHostEntry IPhost = Dns.GetHostByName(Dns.GetHostName());
lblStatus.Text = "IP Address: " + IPhost.AddressList[0].ToString();
nSockets = new ArrayList();
Thread thdListner = new Thread(new ThreadStart(listnerThread));
thdListner.start();
}
2. Network Issue
Take the IP-address used by the code to host the server and Ping the address on the client.
If succeeded, check the firewall settings of the server, client (may temporarly switch of the firewall to check if this is the problem)
If you're using dns names execute an nslookup on the client

Reset backlog after Socket server listen and response client

I am a newbie in C#, and I have developed a Socket program.
private static void SetupServer()
{
Console.WriteLine("Setting up server...");
serverSocket.Bind(new IPEndPoint(IPAddress.Any, 100));
serverSocket.Listen(1);
serverSocket.BeginAccept(new AsyncCallback(AcceptCallback), null);
}
But after server response a client, server is closed and not listen any time. How should I do to reset server after calling Listen(backlog) to maintain server for a long time?
This is my code in ClientSide:
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.Tasks;
using System.Windows.Forms;
namespace PC_Client
{
public partial class Form1 : Form
{
private static Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
public Form1()
{
InitializeComponent();
Console.ReadLine();
}
private void SendLoop()
{
string req = txtRequest.Text;
byte[] buffer = Encoding.ASCII.GetBytes(req);
clientSocket.Send(buffer);
byte[] receiveBuf = new byte[1024];
int rec = clientSocket.Receive(receiveBuf);
byte[] data = new byte[rec];
Array.Copy(receiveBuf, data, rec);
Console.WriteLine("Received: " + Encoding.ASCII.GetString(data));
}
private void LoopConnect()
{
int attempts = 0;
while(!clientSocket.Connected)
{
try
{
attempts++;
clientSocket.Connect(IPAddress.Loopback, 100);
}
catch (SocketException)
{
Console.WriteLine("Connection attempts: " + attempts.ToString());
}
}
//Console.Clear();
Console.WriteLine("Connected");
}
private void button1_Click(object sender, EventArgs e)
{
SendLoop();
}
}
}
I'm not sure about the particulars of C#, but in general, you want to wrap your accept call in a loop like so:
while(true) {
clientSocket = serverSocket.accept();
respond to socket in background thread
}
This way, your main thread will always be able to listen for sockets (because its wrapped in a while loop, and continues to accept new connections) while also not being blocked while handling a client request (because the client socket is handled in a background thread)

SocketException when connecting to server

I am running both client and server on the same machine.
Does any 1 know the error stated above?
server
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.Threading;
using System.Net.Sockets;
using System.IO;
using System.Net;
namespace Server
{
public partial class Server : Form
{
private Socket connection;
private Thread readThread;
private NetworkStream socketStream;
private BinaryWriter writer;
private BinaryReader reader;
//default constructor
public Server()
{
InitializeComponent();
//create a new thread from server
readThread = new Thread(new ThreadStart(RunServer));
readThread.Start();
}
protected void Server_Closing(object sender, CancelEventArgs e)
{
System.Environment.Exit(System.Environment.ExitCode);
}
//sends the text typed at the server to the client
protected void inputText_KeyDown(object sender, KeyEventArgs e)
{
// send the text to client
try
{
if (e.KeyCode == Keys.Enter && connection != null)
{
writer.Write("Server>>> " + inputText.Text);
displayText.Text +=
"\r\nSERVER>>> " + inputText.Text;
//if user at server enter terminate
//disconnect the connection to the client
if (inputText.Text == "TERMINATE")
connection.Close();
inputText.Clear();
}
}
catch (SocketException)
{
displayText.Text += "\nError writing object";
}
}//inputTextBox_KeyDown
// allow client to connect & display the text it sends
public void RunServer()
{
TcpListener listener;
int counter = 1;
//wait for a client connection & display the text client sends
try
{
//step 1: create TcpListener
IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0];
TcpListener tcplistener = new TcpListener(ipAddress, 9000);
//step 2: TcpListener waits for connection request
tcplistener.Start();
//step 3: establish connection upon client request
while (true)
{
displayText.Text = "waiting for connection\r\n";
// accept incoming connection
connection = tcplistener.AcceptSocket();
//create NetworkStream object associated with socket
socketStream = new NetworkStream(connection);
//create objects for transferring data across stream
writer = new BinaryWriter(socketStream);
reader = new BinaryReader(socketStream);
displayText.Text += "Connection " + counter + " received.\r\n ";
//inform client connection was successful
writer.Write("SERVER>>> Connection successful");
inputText.ReadOnly = false;
string theReply = "";
// step 4: read string data sent from client
do
{
try
{
//read the string sent to the server
theReply = reader.ReadString();
// display the message
displayText.Text += "\r\n" + theReply;
}
// handle the exception if error reading data
catch (Exception)
{
break;
}
} while (theReply != "CLIENT>>> TERMINATE" && connection.Connected);
displayText.Text +=
"\r\nUser terminated connection";
// step 5: close connection
inputText.ReadOnly = true;
writer.Close();
reader.Close();
socketStream.Close();
connection.Close();
++counter;
}
} //end try
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
}// end method runserver
}// end class server
client
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.Threading;
using System.Net.Sockets;
using System.IO;
using System.Net;
namespace Client
{
public partial class Client : Form
{
private NetworkStream output;
private BinaryWriter writer;
private BinaryReader reader;
private string message = "";
private Thread readThread;
//default constructor
public Client()
{
InitializeComponent();
readThread = new Thread(new ThreadStart(RunClient));
readThread.Start();
}
protected void Client_Closing(
object sender, CancelEventArgs e)
{
System.Environment.Exit(System.Environment.ExitCode);
}
//sends the text user typed to server
protected void inputText_KeyDown(
object sender, KeyEventArgs e)
{
try
{
if (e.KeyCode == Keys.Enter)
{
writer.Write("CLIENT>>> " + inputText.Text);
displayText.Text +=
"\r\nCLIENT>>> " + inputText.Text;
inputText.Clear();
}
}
catch (SocketException ioe)
{
displayText.Text += "\nError writing object";
}
}//end method inputText_KeyDown
//connect to server & display server-generated text
public void RunClient()
{
TcpClient client;
//instantiate TcpClient for sending data to server
try
{
displayText.Text += "Attempting connection\r\n";
//step1: create TcpClient for sending data to server
client = new TcpClient();
client.Connect("localhost", 9000);
//step2: get NetworkStream associated with TcpClient
output = client.GetStream();
//create objects for writing & reading across stream
writer = new BinaryWriter(output);
reader = new BinaryReader(output);
displayText.Text += "\r\nGot I/O streams\r\n";
inputText.ReadOnly = false;
//loop until server terminate
do
{
//step3: processing phase
try
{
//read from server
message = reader.ReadString();
displayText.Text += "\r\n" + message;
}
//handle exception if error in reading server data
catch (Exception)
{
System.Environment.Exit(System.Environment.ExitCode);
}
} while (message != "SERVER>>> TERMINATE");
displayText.Text += "\r\nClosing connection.\r\n";
//step4: close connection
writer.Close();
reader.Close();
output.Close();
client.Close();
Application.Exit();
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
}
}
It is probably your firewall acting up. Try connecting to something like www.google.com on TCP 80 just to see if you can actually connect.
Are you using a newer version of Windows? It's possible that you're only listening on IPv4, but "localhost" is resolving to an IPv6 address and it's not finding it. Try connecting to "127.0.0.1" instead of localhost and see if the result changes.
mk,
I'd tcplistener/tcpclient for simple applications . . .
TheEruditeTroglodyte
If you use that constructor with TCPListener then it will let the underlying service provider pick a network address, which probably won't be 'localhost'. You're probably listening on your LAN/WLAN card instead of localhost.
Take a look at the MSDN page for TCPListener, the sample there shows how to use a different constructor, look at the other constructors for more samples.
Here's one way:
IPAddress ipAddress = Dns.Resolve("localhost").AddressList[0];
TcpListener tcpListener = new TcpListener(ipAddress, 9000);

Categories