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
Related
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 .
So I just want to make it clear that I am very new to Tcp / IP programming in C#. Also, I've changed the IP's in the question to not match the ones in my project due not not wanting to leak it.
When ever I start the project it should open 2 forms (Client & server)
but for some reason it only opens the Client winform application.
(I've changed the start method in the project settings to start both)
My best guess would be that its stuck on trying to start the TcpListener when ever I call it in the Form_Load event.
Why is this happening and how do I fix it?
Here is the server (the one that doesnt start)
using System;
using System.Windows.Forms;
using System.Net.Sockets;
using System.IO;
using System.Net;
namespace SimpleServer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string rd;
byte[] b1;
string v;
int m;
//TcpListener list;
Int32 port = 8080;
Int32 port1 = 8080;
IPAddress localAddr = IPAddress.Parse("192.168.0.1");
private void BrowseBtn_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = folderBrowserDialog1.SelectedPath;
TcpListener list = new TcpListener(localAddr, port1);
//list = new TcpListener(port1);
list.Start();
TcpClient client = list.AcceptTcpClient();
Stream s = client.GetStream();
b1 = new byte[m];
s.Read(b1, 0, b1.Length);
File.WriteAllBytes(textBox1.Text + "\\" + rd.Substring(0, rd.LastIndexOf('.')), b1);
list.Stop();
client.Close();
statusLabel.Text = "File Received......";
}
}
private void Form1_Load(object sender, EventArgs e)
{
IPAddress localAddr = IPAddress.Parse("192.168.0.1"); //changed it from my main ip
TcpListener list = new TcpListener(localAddr, port);
//TcpListener list = new TcpListener(port);
list.Start();
TcpClient client = list.AcceptTcpClient();
MessageBox.Show("Client trying to connect");
StreamReader sr = new StreamReader(client.GetStream());
rd = sr.ReadLine();
v = rd.Substring(rd.LastIndexOf('.') + 1);
m = int.Parse(v);
list.Stop();
client.Close();
}
}
}
And here is the client source 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.Sockets;
using System.IO;
namespace SimpleClient
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string n;
byte[] b1;
OpenFileDialog op;
private void browseButton_Click(object sender, EventArgs e)
{
op = new OpenFileDialog();
if (op.ShowDialog() == DialogResult.OK)
{
string t = textBox1.Text;
t = op.FileName;
FileInfo fi = new FileInfo(textBox1.Text = op.FileName);
n = fi.Name + "." + fi.Length;
TcpClient client = new TcpClient("22.232.23.22", 8080);
StreamWriter sw = new StreamWriter(client.GetStream());
sw.WriteLine(n);
sw.Flush();
statusLabel.Text = "File Transferred....";
}
}
private void sendBtn_Click(object sender, EventArgs e)
{
TcpClient client = new TcpClient("22.232.23.22", 8080);
Stream s = client.GetStream();
b1 = File.ReadAllBytes(op.FileName);
s.Write(b1, 0, b1.Length);
client.Close();
statusLabel.Text = "File Transferred2....";
}
}
}
You can only have one startup project in a solution... Right Click Project in Solution Explorer and choose "Set as Startup Project"
When you deploy the exe's you will have to start the server Exe either manually, by Scheduled Task or better yet make the Server Exe run as a Service.
Another way you could do it is System.Diagnostic.Process.Start("..\bin\Debug\SimpleServer.exe");
The issue was that it couldnt connect because the ip adresses didnt match in the client and the server. Both had to be a IPV4 adress.
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)
I wrote a C# TCP Server that runs on my desktop, while I have a client running on my windows phone. It works great, the client can connect to the server. But I am trying to make it so the server can receive messages from the client. When I run it, the server just receives a number when I am sending a string.
Here is my server code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.Net;
using System.IO;
namespace TCPServer
{
class Server
{
private TcpListener tcpListener;
private Thread listenThread;
public Server()
{
this.tcpListener = new TcpListener(IPAddress.Any, 80);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
TcpClient client = this.tcpListener.AcceptTcpClient();
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
Console.WriteLine("Got connection");
StreamReader clientStreamReader = new StreamReader(clientStream);
Console.WriteLine(clientStreamReader.Read());
}
}
}
Here is the client 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;
namespace NetworkingTesting
{
class Client
{
Socket socket = null;
static ManualResetEvent clientDone = new ManualResetEvent(false);
const int TIMEOUT_MILLISECONDS = 5000;
const int MAX_BUFFER_SIZE = 2048;
DnsEndPoint hostEntry;
public string Connect(string hostName, int portNumber)
{
string result = string.Empty;
hostEntry = new DnsEndPoint(hostName, portNumber);
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
SocketAsyncEventArgs socketEventArg = new SocketAsyncEventArgs();
socketEventArg.RemoteEndPoint = hostEntry;
socketEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(delegate(object s, SocketAsyncEventArgs e)
{
result = e.SocketError.ToString();
clientDone.Set();
});
clientDone.Reset();
socket.ConnectAsync(socketEventArg);
clientDone.WaitOne(TIMEOUT_MILLISECONDS);
return result;
}
public void SendToServer(string message)
{
SocketAsyncEventArgs asyncEvent = new SocketAsyncEventArgs { RemoteEndPoint = hostEntry};
Byte[] buffer = Encoding.UTF8.GetBytes(message + Environment.NewLine);
asyncEvent.SetBuffer(buffer, 0, buffer.Length);
socket.SendAsync(asyncEvent);
}
}
}
In my main client class, I have: client.SendToServer("hello!");
When I run the server and run the client the server detects the client but receives "104" instead of "Hello". Could anybody explain why this is happening and maybe provide a solution to the problem?
When you're doing clientStreamReader.Read() you're just reading one char as int from the stream. Check the doc here.
That's why you get only a number.
You need a delimeter to each message to know where it ends, \r\n is often used.
Here a sample to make your server receive your hello! String :
In your client Code
client.SendToServer("hello!" + "\r\n");
In your server Code
Console.WriteLine(clientStreamReader.ReadLine()); // Which should print hello!
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