file upload error - c#

Here is my code at both client side and server side. My code is simple, just upload a file to an ASP.Net web site.
My client code throws exception when it works on Vista (x64, Enterprise, SP1), but works fine on Windows Server 2003.
Any ideas?
10.10.12.162 is my server address.
[Code]
Client:
static void Main(string[] args)
{
Console.Write("\nPlease enter the URI to post data to : ");
String uriString = Console.ReadLine();
WebClient myWebClient = new WebClient();
Console.WriteLine("\nPlease enter the fully qualified path of the file to be uploaded to the URI");
string fileName = Console.ReadLine();
Console.WriteLine("Uploading {0} to {1} ...", fileName, uriString);
DateTime begin = DateTime.Now;
byte[] responseArray = null;
try
{
responseArray = myWebClient.UploadFile(uriString, fileName);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.ToString());
}
DateTime end = DateTime.Now;
Console.WriteLine("Elapsed time is: {0}", (end - begin).TotalMilliseconds);
}
Server:
public partial class FileUploadHandler : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
foreach (string f in Request.Files.AllKeys)
{
HttpPostedFile file = Request.Files[f];
file.SaveAs("D:\\UploadFile\\UploadedFiles\\" + file.FileName);
}
}
}
Exception from client side:
Unable to connect to the remote server
System.Net.WebException: Unable to connect to the remote server ---> System.Net.
Sockets.SocketException: No connection could be made because the target machine
actively refused it 10.10.12.162:1031
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddre
ss socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Sock
et s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state,
IAsyncResult asyncResult, Int32 timeout, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.WebClient.UploadFile(Uri address, String method, String fileNam
e)
at FileUploadClient.Program.Main(String[] args) in D:\UploadFile\FileUploadClient\Program.cs:line 30
[/Code]
regards,
George

There's nothing about that code which would alarm me too much.
Open a remote desktop on the machine that is causing you problems.
Open a command line.
Issue the command:
telnet 10.10.12.162 1031
Do you see a cursor, or does telnet give you an error that it cannot connect? If you get an error from telnet, you probably have a NIC issue/firewall issue/router issue/other connectivity issue unrelated to your code.

Related

Server Timeout C#

So, I'm developing a client-side application in C# that connects to a server side application (also written in C#). To begin with, I am just trying to get the applications to successfully communicate with one another. Currently, I have both the client and server running on the same device.
Server Side
On the server side, I'm using a TcpListener to accept a socket, printing out that it has connected for debugging purposes, receiving a request, and sending a response. The code can be found below:
Server Side Code:
while (true)
{
// Accept a new connection
Socket socket = socketListener.AcceptSocket();
if (socket.Connected)
{
Console.WriteLine("\nClient Connected!!\n==================\nClient IP {0}\n", socket.RemoteEndPoint);
// Make a byte array and receive data from the client
byte[] receive = new byte[1024];
_ = socket.Receive(receive, receive.Length, 0);
// Convert byte to string
string buffer = Encoding.ASCII.GetString(receive);
string response = "Test response";
int numBytes = 0;
try
{
if (socket.Connected)
{
if ((numBytes = socket.Send(data, data.Length, 0)) == -1)
Console.WriteLine("Socket Error: cannot send packet");
else
Console.WriteLine("No. of bytes sent {0}", numBytes);
}
else
{
Console.WriteLine("Connection Dropped...");
}
}
catch (Exception e)
{
Console.WriteLine("An exception has occurred: " + e.ToString());
}
}
}
Client Side
On the client side, I'm using a TcpClient to connect to the server using an IP address (In this case it's 127.0.0.1), establishing a NetworkStream object, sending a request, and reading a response.
Client-Side Code:
private static readonly TcpClient socket = new TcpClient();
private const string IP = "127.0.0.1";
private const int PORT = 46495;
static void Main(string[] args)
{
try
{
socket.Connect(IP, PORT);
}
catch (Exception)
{
Console.WriteLine("Error connecting to the server.");
return;
}
NetworkStream stream = socket.GetStream();
stream.ReadTimeout = 2000;
string request = "Test Request";
byte[] bytes = Encoding.UTF8.GetBytes(request);
stream.Write(bytes, 0, bytes.Length);
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
try
{
string response = reader.ReadToEnd();
Console.WriteLine(response);
}
catch(Exception e)
{
Console.WriteLine(e);
}
}
The Output
On the server side, everything appears to be fine. The client connects successfully with the expected IP address, I get the expected request, and the correct response appears to have been sent successfully.
The client-side is where it gets more complicated. Where I would expect the "Test Response" response, instead I get a SocketException that from what I understand indicates a timeout??? The full output can be found below:
System.IO.IOException: Unable to read data from the transport connection: A connection attempt failed because the connected party did not properly respond after a period of time, or an established connection failed because the connected host has failed to respond...
---> System.Net.Sockets.SocketException (10060): A connection attempt failed because the connected party did not properly respond after a period of time, or an established connection failed because the connected host has failed to respond.
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 size)
at System.IO.StreamReader.ReadBuffer()
at System.IO.StreamReader.ReadToEnd()
at Client.Client.Main(String[] args) in C:\Dev\Project Orange Sunshine\Project Orange Sunshine\Client\Client.cs:line 38
What I have tried
To begin I wanted to ensure that my server was in fact sending a response in the first place. To test this, I tried accessing the server application through a web browser. Sure enough, I got a blank page with the expected "Test Response" text in the top left corner. This, to me, indicates my server application is working as expected.
Through some googling, I have found a variety of answers to similar questions stating that it is likely that the Windows Defender Firewall is blocking the port that is being used. For testing purposes, I tried disabling the firewall entirely for private networks such as the one that I am on. This didn't change anything, unfortunately.
I feel like I am missing something obvious and any input would be greatly appreciated.
Cheers!
StreamReader.ReadToEnd() on a NetworkStream will only return once the "end" of the stream is reached, which doesn't happen in your example; thus, the StreamReader times out.
You should fix this by using the lower-level NetworkStream.Read method to read from the stream:
var buffer = new byte[4096];
var bytesRead = stream.Read(buffer, 0, buffer.Length);
Console.WriteLine("Read {0} bytes", bytesRead);
string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine(response);
To make this test program more robust, you will also need to introduce "framing", i.e., some way for the server to indicate to the client that it can stop reading. This can be a terminator suffix, such as \r\n used by HTTP, or a length prefix that is sent upfront to tell the client how many more bytes to read.

How to send data from C# to python using sockets?

I cannot find any example or a tutorial on how to send data from C# to python.
in my application, C# is supposed to keep reading data from a hardware and send it to python to be processed. i have tried to create a basic server on python and a basic client on C# and i was never able to establish connection between the client and the server with the following output from C# No connection could be made because the target machine actively refused it. i tested my python server on a python client and i was able to establish connection just fine.
how do i send data from C# to python correctly using sockets? is there any available tutorial on example i can follow? is there something wrong with my code? here it is:
Python Server code:
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((socket.gethostname(), 1234))
s.listen(5)
while True:
clientsocket, address = s.accept()
print(f"Connection from {address} has been established!")
clientsocket.send(bytes("Welcome to the server!", "utf-8"))
clientsocket.close()
C# Client Code:
static void ExecuteClient()
{
try
{
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddr, 1234);
Socket sender = new Socket(ipAddr.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
try
{
sender.Connect(localEndPoint);
Console.WriteLine("Socket connected to -> {0} ",
sender.RemoteEndPoint.ToString());
byte[] messageReceived = new byte[1024];
int byteRecv = sender.Receive(messageReceived);
Console.WriteLine("Message from Server -> {0}",
Encoding.ASCII.GetString(messageReceived, 0, byteRecv));
sender.Shutdown(SocketShutdown.Both);
sender.Close();
}
// Manage of Socket's Exceptions
catch (ArgumentNullException ane)
{
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
}
catch (SocketException se)
{
Console.WriteLine("SocketException : {0}", se.ToString());
}
catch (Exception e)
{
Console.WriteLine("Unexpected exception : {0}", e.ToString());
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
I know this question is old, but incase some else stumbles here in their internet searching.
I just started down the road of learning Python and I'm working on a similar situation with my Raspberry Pi (SERVER) and Windows PC (CLIENT).
The problem is you're making a call to get the hostname on each machine. This is will obviously be different. Your client needs to connect to the address of the server. Your client code is trying to connect to the machine it's running and that connection is being refused. The server is never contacted.
I made the following changes and was able to establish a connection.
Python Server code:
s.bind(("", 1234))
C# Client Code:
//IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
//IPAddress ipAddr = ipHost.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("[SERVER IP]"), 1234);
Server Console Response:
Connection from ('[CLIENT IP]', 52074) has been established!
Client Console Response:
Socket connected to -> [::ffff:[SERVER IP]]:1234
Message from Server -> Welcome to the server!

Socket Exception error

I have a networking socket program in C#.net.
I have to connect with an ip: 169.254.74.65 and port:7998 and my ip is:169.254.74.63.
So I have this code:
using System;
using System.Net;
using System.Net.Sockets;
class MyTcpListener{
public static void Main(){
TcpListener server = null;
try{
Int32 port = 7998;
IPAddress localAddr = IPAddress.Parse("169.254.74.65");
server = new TcpListener(localAddr, port);
server.Start();
Byte[] bytes = new Byte[500];
String data = null;
while (true){
Console.Write("Waiting for a connection... ");
TcpClient client = server.AcceptTcpClient();
data = null;
NetworkStream stream = client.GetStream();
int i;
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0){
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
}
client.Close();}
}
catch (SocketException e){
Console.WriteLine("SocketException: {0}", e);}
finally{ server.Stop(); }
Ping works fine between two IPs. Even telnet 169.254.74.65 7998 gives me proper result and listens to the correct messages. So the connection is solid.
But when I run the above code it shows an exception:
> SocketException: System.Net.Sockets.SocketException (0x80004005): The requested address is not valid in its context
at System.Net.Sockets.Socket.UpdateStatusAfterSocketErrorAndThrowException(SocketError error, String callerName)
at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Bind(EndPoint localEP)
at System.Net.Sockets.TcpListener.Start(Int32 backlog)
at System.Net.Sockets.TcpListener.Start()
at MyTcpListener.Main() in C:\Users\Administrator\source\repos\TCPListener\TCPListener\Program.cs:line 12
What is the problem here?
Your code works for me:
Have you actually hit your server at 127.0.0.1:7998 from a client socket code?
Update
So your Server IP is 169.xx.xx.65, while your own DEV machine IP is 169.xx.xx.63
Your code is something which creates a TCP Server connection. While (if I am not wrong) - you only need to connect to that HL7 machine.
Understand that the HL7 machine will be the server and your machine will be the client. So you just need TcpClient. Something like:
TcpClient client = new TcpClient("169.xx.xx.65", 7998);
Use Connect/GetStream etc methods per: https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient(v=vs.110).aspx

Socket not being closed properly

Using the code as provided here.
When run consecutive times within 120 seconds, fails on my machine with a SocketException:
Only one usage of each socket address (protocol/network address/port) is normally permitted 127.0.0.1:24125
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
Windows 10 x64
Adding socket.Close(); after socket.Receive(receiveBuffer); does nothing. Perhaps obvious because Dispose() should call Close() automatically anyway.
There is no difference in behaviour if ported to F#. So it's to do with how the .NET libraries are being used rather than anything language specific (again, sorry if that's obvious).
The same occurs if the output .exe is run from Windows Command Prompt or from the debugger.
After socket is disposed in code, waiting longer than 120 seconds resets the socket and it can be used once more without error.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace tcpTestCSharp
{
class Program
{
static void Main(string[] args)
{
string response = "Hello";
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
if (ipAddress != null)
{
IPEndPoint serverEndPoint = new IPEndPoint(ipAddress, 24125);
byte[] receiveBuffer = new byte[100];
try
{
using (TcpClient client = new TcpClient(serverEndPoint))
{
using (Socket socket = client.Client)
{
socket.Connect(serverEndPoint);
byte[] data = Encoding.ASCII.GetBytes(response);
socket.Send(data, data.Length, SocketFlags.None);
socket.Receive(receiveBuffer);
Console.WriteLine(Encoding.ASCII.GetString(receiveBuffer));
}
}
}
catch (SocketException socketException)
{
Console.WriteLine("Socket Exception : ", socketException.Message);
throw;
}
Console.ReadLine();
}
}
}
}

TcpListener & Socket connection fails

My friend runs a simple C# Console Application that starts a TcpListener on Port 8484. This is how it's being done:
public static void Listen()
{
Listener = new TcpListener(IPAddress.Any, 8484);
Listener.Start();
Listener.BeginAcceptSocket(new AsyncCallback(EndAccept), null);
}
public static void EndAccept(IAsyncResult IAR)
{
Console.WriteLine("Connection accepted on Port 8484.");
Socket socket = Listener.EndAcceptSocket(IAR);
Instance = new Client(socket);
Listener.Stop();
Listener = null;
}
I connect to him using:
public void Connect()
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
_socket.Connect(IP, Port);
Debug.WriteLine("Connected with server!");
}
catch (Exception ex)
{
Debug.WriteLine(TypeName + " [ERROR] Could not connect to server # {0}:{1}: {2}", IP, Port, ex.Message);
}
}
However, for some reason - he can't accept the connection, it says it doesn't respond. Port 8484 is 100% opened at his computer.
Why does this happen?
Use telnet to verify connectivity to the remote server. E.g. run the command "telnet ip_address port". If it successfully connects then you can reach the server. If telnet cannot connect then you cannot reach the server, likely due to a firewall issue.
Try disabling the firewall.1
1 - Helped user in chat to test for firewall problems, and it has not open. That has the problem

Categories

Resources