There are three apps run at the same time, 2 clients and 1 server. The whole system should function as following:
The client sends an serialized object to server then server receives that object as a stream, finally the another client get that stream from server and deserialize it.
This is the sender:
TcpClient tcpClient = new TcpClient();
tcpClient.Connect("127.0.0.1", 8888);
Stream stream = tcpClient.GetStream();
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(stream, event); // Event is the sending object
tcpClient.Close();
Server code:
TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 8888);
listener.Start();
Console.WriteLine("Server is running at localhost port 8888 ");
while (true)
{
Socket socket = listener.AcceptSocket();
try
{
Stream stream = new NetworkStream(socket);
// Typically there should be something to write the stream
// But I don't knwo exactly what should the stream write
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
Console.WriteLine("Disconnected: {0}", socket.RemoteEndPoint);
}
}
The receiver:
TcpClient client = new TcpClient();
// Connect the client to the localhost with port 8888
client.Connect("127.0.0.1", 8888);
Stream stream = client.GetStream();
Console.WriteLine(stream);
when I run only the sender and server, and check the server, server receives correctly the data. The problem is when I run the receiver, everything is just disconnected. So where is my problem ? Could anyone point me out ? Thanks
Related
I write a client - server utility which transmits a xml document over TCP network. The simplest way to do it is subj. But how can I use the same stream to write back to the client after the xml was handled on the server? Here one of varints I've tried to use.
server:
IPAddress ipAddress = IPAddress.Any;
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
TcpListener Listener = new TcpListener(localEndPoint);
Listener.Start();
Console.WriteLine("Waiting for a connection...");
TcpClient tcpClient = Listener.AcceptTcpClient();
NetworkStream stream = tcpClient.GetStream();
XDocument xmlNewInit = XDocument.Load(stream);
// Send back a response.
byte[] msg = Encoding.ASCII.GetBytes("Object created!");
stream.Write(msg, 0, msg.Length);
client:
IPAddress ipAddress = IPAddress.Parse("192.168.1.49");
IPEndPoint remoteEP = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
TcpClient tcpClient = new TcpClient();
// Connect the socket to the remote endpoint. Catch any errors.
tcpClient.Connect(remoteEP);
textBox.Text = "Socket connected to " + remoteEP.ToString();
NetworkStream stream = tcpClient.GetStream();
XElement NewInit = new XElement(.....)
NewInit.Save(stream);
// Receive the response from the remote device.
int bytesRec = stream.Read(bytes, 0, bytes.Length);
textBox.Text = Encoding.ASCII.GetString(bytes, 0, bytesRec);
I works fine when I just send the XML. But when I add strings handling the response it freezes infinitely and not even the XML is sent any more.
I've tried also to use AutoResetEvent to wait till the XML is sent and handle the response only after that, but with the same result.
Surely there are means to do the task. Please, help!
I am trying to send a message from my laptop to my desktop over the LAN.
I have written a Tcp server that listens for a connection on a port, and a client that tries to connect to it and send a simple string as a message.
Server:
void Listen()
{
listener = new TcpListener(IPAddress.Any, port);
listener.Start();
while (true)
{
Debug.Log($"listening to {listener.LocalEndpoint}...");
var socket = listener.AcceptSocket();
Debug.Log("connected!");
var bytes = new byte[100];
int k = socket.Receive(bytes);
var data = Encoding.ASCII.GetString(bytes, 0, k);
Debug.Log(data);
socket.Send(new byte[] {1});
Debug.Log("responded");
socket.Close();
Debug.Log("closed connection");
}
}
Client:
public void Send()
{
client = new TcpClient();
Debug.Log("connecting...");
client.Connect("192.168.0.12", port);
Debug.Log("connected!");
var data = Encoding.ASCII.GetBytes("Hello!");
var stream = client.GetStream();
Debug.Log("sending data");
stream.Write(data, 0, data.Length);
Debug.Log("data sent! waiting for response...");
var reply = new byte[100];
stream.Read(reply,0,100);
Debug.Log("received response");
client.Close();
}
They communicate correctly when they are both on the same machine, but the client never connects to the server when I am running it on a different machine.
I have a rule in my firewall that allows an incoming connection through the port I have specified.
I have tried it with both computer's firewalls off and the connection still doesn't go through.
Any help would be greatly appreciated.
I'm creating a small chat (1-1) application to learn network programming and when creating the socket using TCP protocol, the Socket.Connect() always return error 10061.
However, if I make the socket UDP, I don't see the issue.
Here is my code:
myEndPoint = new IPEndPoint(IPAddress.Parse(_txtMyIPAdress.Text), int.Parse(_txtMyPort.Text));
TargetSideEndPoint = new IPEndPoint(IPAddress.Parse(_txtTargetIPAddress.Text), int.Parse(_txtTargetPort.Text));
mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
mySocket.Bind(myEndPoint);
mySocket.Connect(TargetSideEndPoint);
byte[] receivedBuffer = new byte[MAX_BUFFER_SIZE = 1024];
ReceivePackets(mySocket, receivedBuffer);//My function
Can any one help me?
Update:
I'm not using Listen() the issue is when I call Connect()
I already tried multiple ports with the same issue and I'm currently testing on 1 PC by opening 2 instances from my application and using 2 different ports while firewall is off.
Thanks,
For TCP, which is a connection oriented protocol, you would need a server and a client.
The server must listen for incoming connections and the client should initiate the connection. Then, the client will be able to communicate with the server and exchange data.
Here is a simple working example:
void Main()
{
Console.WriteLine("Starting listener thread");
Thread serverThread = new Thread(ListenerThreadProc);
serverThread.Start();
Console.WriteLine("Waiting 500 milliseconds to allow listener to start");
Thread.Sleep(500);
Console.WriteLine("Client: Connecting to server");
TcpClient client = new TcpClient();
client.Connect(IPAddress.Loopback, 12345);
Console.WriteLine("Client: Connected to server");
byte[] buffer = new byte[5];
Console.WriteLine("Client: Receiving data");
using (NetworkStream clientStream = client.GetStream())
clientStream.Read(buffer, 0, buffer.Length);
Console.WriteLine("Client: Received data: " + buffer.Aggregate("", (s, b) => s += " " + b.ToString()));
}
void ListenerThreadProc()
{
TcpListener listener = new TcpListener(IPAddress.Any, 12345);
listener.Start();
Console.WriteLine("Server: Listener started");
Console.WriteLine("Server: Waiting for client to connect");
TcpClient client = listener.AcceptTcpClient();
Console.WriteLine("Server: Client connected");
listener.Stop();
Console.WriteLine("Server: Listener stopped");
Console.WriteLine("Server: Sending data");
byte[] buffer = new byte[] { 1, 2, 3, 4, 5 };
using (NetworkStream clientStream = client.GetStream())
clientStream.Write(buffer, 0, buffer.Length);
Console.WriteLine("Server: Sent data");
}
In this example, made as simple as it gets, you have a server accepting a single client to which it sends some data. The client connects, reads the data and then displays it.
A real-life server would spin new threads (or tasks, for async model) to serve the client's request as soon as the client would connect and carry on listening for new connections.
I have an issue with a TCP Listener.
The scenario is the following:
- I am receiving TCP packets (8192 Bytes each) and I would like to dump the data received from NetworkStream into a file (using FileStream);
- What I saw is that all the TCP packets arrived to the TCP listener but only the first 8192 Bytes are dumped into the file.
I believe that the NetStream is faster than the IO operation to the file.
My code is:
try
{
// Set TcpListener on port 8
Int32 portN = 8;
TcpListener server = new TcpListener(IPAddress.Any, portN);
// Start listening for client requests
server.Start();
Console.Write("Waiting for connection... ");
// Define File Name
string RcvFileName = #"c:\ethernet\out_file.raw";
// Buffer for reading data
int NrBytesRec;
Byte[] RecData = new Byte[8192];
// enter into listening loop
while (true)
{
// Perform a blocking call to accept requests.
// You can also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
// Get a stream object for reading and writing
NetworkStream netstream = client.GetStream();
// Append data into file
FileStream fs_wr = new FileStream(RcvFileName, FileMode.Append, FileAccess.Write);
// Dump data
while ((NrBytesRec = netstream.Read(RecData, 0, RecData.Length)) > 0)
{
fs_wr.Write(RecData, 0, NrBytesRec);
Console.WriteLine("Received: {0}", NrBytesRec);
}
netstream.Close();
fs_wr.Close();
//client.Close();
}
I have a server listened on a socket. This server is a Windows Service.
My problem is: When I disconnect a client socket.Disconnect(false); the service so closed and other clients are closed forcibly or new connections refused. I think that when service kill this client thread, the service not back to main thread.
Paste my code used for service (server functionality). Is correct the management of threads?
I run server with
this.tcpListener = new TcpListener(ipEnd);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
}
tcpClient.Close();
}
Sorry for my bad english and thanks for any suggestion
The code you provided seems to be almost correct.
The only reason your app will crash is the line
NetworkStream clientStream = tcpClient.GetStream();
If you look at the documentation for GetStream(), you could see that it can throw InvalidOperationException if client is not connected. So in the situation when client connects and immediately disconnects it could be an issue.
So just guard this code with try-catch.
Also sometimes you might not get an explicit exception report, but have crash in multithreaded applications. To handle such exceptions subscribe to the AppDomain.CurrentDomain.UnhandledException event.