Reputation: 2396
good day all
I am going over some network programming to implement with a larger application, but for basics, I am creating a simple network chat server client application with the help of this link
what should happen:
When receiving the data from the client, the message box pops up showing a socket connection to my PC ip address with port, but
Problem:
the messagebox which displays the message sent is empty (aka ""), I do not understand what I am doing wrong.
Advice?
had a look at this, but I do not think this is appropriate for my situation network stream with buffers
client (sends data)
const int _PORT = 80;
public Form1()
{
InitializeComponent();
}
private void sendText(string _reciever_ip, string _MESSAGE)
{
TcpClient _sender = new TcpClient(_reciever_ip, _PORT);
try
{
Stream s = _sender.GetStream();
StreamWriter sw = new StreamWriter(s);
sw.WriteLine(_MESSAGE);
s.Close();
}
catch (Exception x)
{
MessageBox.Show(x.ToString());
}
_sender.Close();
}
private void button2_Click(object sender, EventArgs e)
{
sendText(inputT_IP.Text, inputT_Msg.Text);
}
server (recieves data)
const int _PORT = 80;
static List<string> _ipaddress_list = new List<string>();
public Form1()
{
InitializeComponent();
}
private void recieveText(string _IPADDRESS)
{
//open a listener for a tcp client, to the same for UDp client
TcpListener _reciever_client = new TcpListener(IPAddress.Parse(_IPADDRESS), _PORT); //how would you listen for a connection from any port?
_reciever_client.Start();
while (true)
{
Socket _listener_socket = _reciever_client.AcceptSocket();
try
{
MessageBox.Show("Recieving from : " + _listener_socket.RemoteEndPoint.ToString());
Stream _net_stream = new NetworkStream(_listener_socket);
StreamReader sr = new StreamReader(_net_stream);
MessageBox.Show(sr.ReadLine());
//richTextBox1.AppendText();
}
catch (Exception x)
{
MessageBox.Show(x.ToString());
}
_listener_socket.Close();
}
}
void GetLocalIPAddress()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
_ipaddress_list.Add(ip.ToString());
}
}
}
private void button1_Click(object sender, EventArgs e)
{
GetLocalIPAddress();
foreach (string item in _ipaddress_list)
{
(new Thread(() => recieveText(item))).Start();
}
}
Upvotes: 0
Views: 2336
Reputation: 180867
A StreamWriter buffers writes, so your code;
Stream s = _sender.GetStream();
StreamWriter sw = new StreamWriter(s);
sw.WriteLine(_MESSAGE);
s.Close();
...actually writes to the StreamWriter's in memory buffer and closes the socket before the data has been passed from the StreamWriter to the network.
If you instead close the StreamWriter;
Stream s = _sender.GetStream();
StreamWriter sw = new StreamWriter(s);
sw.WriteLine(_MESSAGE);
sw.Close();
...Close()
actually flushes the buffer to the underlying socket, and then closes the underlying socket after the data has been sent.
Upvotes: 3