I am trying to send a message between 2 computers. I have been able to establish connection but for some weird reason i have been unable to acquire stream.
Server Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace chat_server
{
class Program
{
static void Main(string[] args)
{
TcpListener server = new TcpListener(IPAddress.Any, 9999);
server.Start();
Console.WriteLine("Waiting for client connections");
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Client request accepted");
NetworkStream stream = client.GetStream();
StreamReader reader = new StreamReader(stream);
StreamWriter writer = new StreamWriter(stream);
Console.WriteLine("The message is " + reader.ReadToEnd());
}
}
}
Client Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace chat_client
{
class Program
{
static void Main(string[] args)
{
TcpClient client = new TcpClient("localhost", 9999);
NetworkStream stream = client.GetStream();
StreamReader reader = new StreamReader(stream);
StreamWriter writer = new StreamWriter(stream);
writer.Write("Hello world");
Console.WriteLine("Message Sent");
Console.ReadKey();
}
}
}
My server code confirms client connection by printing client request accepted. However for some reason i am unable to acquire data from stream. Quick Help would be really appreciated.
Thank you
You need to flush the stream in order to actually send the data.
Try:
Take a look at the MSDN docs for more information:
Synchronous socket server: http://msdn.microsoft.com/en-us/library/6y0e13d3.aspx
Asynchronous socket server: http://msdn.microsoft.com/en-us/library/5w7b7x5f.aspx
Here’s a site that explains in more detail the ins and outs of sockets: http://nitoprograms.blogspot.co.uk/2009/04/tcpip-net-sockets-faq.html