c# - networkstream read and write - c#

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();
}
}

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.

Related

Receiving data all the time

so made client-server-client tcp/ip app in c# that are supposed to communicate between 2 computers that are in different network.
I have few problems , first of them my server wont start on my public ip sayings its not valid in this context. Second is that I need to press send button twice before it sends data to server ,and then server 2 variations of data, one in bytes, other in char how its supposed to be. And third is how to make clients trying to receive data whole time. Should I have connection between clients have open whole time? I tried using timers to check if there is data to be received from the server.
Server code
static void Main(string[] args)
{
TcpListener server = new TcpListener(IPAddress.Parse("192.168.0.13"), 8080);
TcpClient client = default(TcpClient);
TcpClient client2 = default(TcpClient)
try
{
server.Start();
Console.WriteLine("Server started...");
}
catch(Exception ex)
{
Console.WriteLine("Server failed to start... {0}",ex.ToString());
Console.Read();
}
while (true)
{
client = server.AcceptTcpClient(); /
byte[] receivedBuffer = new byte[1000];
NetworkStream stream = client.GetStream();
stream.Read(receivedBuffer,0,receivedBuffer.Length);
StringBuilder message = new StringBuilder(); foreach (byte b in receivedBuffer)
{
if (b.Equals(126)
) //proveramo d {
break;
}
else
{
message.Append(Convert.ToChar(b).ToString()); }
}
client2 = server.AcceptTcpClient();
byte[] receivedBuffer2 = new byte[1000];
NetworkStream stream2 = client2.GetStream();
stream2.Read(receivedBuffer2, 0, receivedBuffer2.Length);
StringBuilder message2 = new StringBuilder();
foreach (byte g in receivedBuffer2)
{
if (g.Equals(126))
{
break;
}
else
{
message2.Append(g);
}
}
stream2.Write(receivedBuffer, 0, receivedBuffer.Length);
stream.Write(receivedBuffer2,0,receivedBuffer2.Length);
Console.WriteLine(message2.ToString());
Console.WriteLine(message.ToString());
}
Client code
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer1.Start();
}
private int port = 8080;
private void submit_Click(object sender, EventArgs e)
{
TcpClient client = new TcpClient("192.168.0.13",port);
TcpListener listener = new TcpListener(IPAddress.Parse("192.168.0.13"), port);
long byteCount = Encoding.ASCII.GetByteCount(messagebox_TB.Text + 1); byte[] sentDataBytes = new byte[byteCount];
sentDataBytes = Encoding.ASCII.GetBytes(messagebox_TB.Text + "~");
NetworkStream stream = client.GetStream();
stream.Write(sentDataBytes,0,sentDataBytes.Length);
stream.Close();
client.Close();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
long a = 0;
try
{
TcpClient client = new TcpClient("192.168.0.13", port);
TcpListener listener = new TcpListener(IPAddress.Parse("192.168.0.13"), port);
NetworkStream stream = client.GetStream();
byte[] receviedBytes = new byte[100];
stream.Read(receviedBytes, 0, receviedBytes.Length);
StringBuilder
message = new StringBuilder();
foreach (byte b in receviedBytes) {
if (b.Equals(126)
) //proveramo {
break;
}
else
{
message.Append(Convert.ToChar(b).ToString()); }
}
textBox1.Text = message.ToString();
client.Close();
stream.Close();
}
catch
{
a++;
}
}
}

TCPListener in windows form

I am trying to write a TCP listener that can connect to multiple clients and send and receive data.
Some of my code -
Calling server -
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'cresijCamDataSet1.CentralControl' table. You can move, or remove it, as needed.
this.centralControlTableAdapter1.Fill(this.cresijCamDataSet1.CentralControl);
s = new Server();
Thread th = new Thread(s.Run);
th.Start();
}
Run Method -
public async void Run()
{
tcp = new TcpListener(IPAddress.Any, 1200);
tcp.Start();
while (true)
{
try
{
TcpClient client = await tcp.AcceptTcpClientAsync();
Thread th = new Thread(()=>{
Process(client);
}) ;
}
catch (Exception ex)
{
string m = ex.Message;
}
}
}
private async Task Process(TcpClient tcpClient)
{
bool hasItem = clients.Contains(tcpClient);
if(hasItem == false)
{
clients.Add(tcpClient);
}
IPEndPoint iPEndPoint =(IPEndPoint) tcpClient.Client.RemoteEndPoint;
string ip = ((IPEndPoint)tcpClient.Client.RemoteEndPoint).Address.ToString();
NetworkStream stream = tcpClient.GetStream();
byte[] receivedBytes = new byte[tcpClient.ReceiveBufferSize];
stream.Read(receivedBytes, 0, receivedBytes.Length);
f.UpdateData(receivedBytes, ip);
}
Sender Method to send data -
public void Sender(byte[] data, TcpClient client)
{
NetworkStream stream = client.GetStream();
stream.Write(data, 0, data.Length);
}
As you can see I have called Run() method in formLoad. But this all is not working as I dont have much knowledge of threads.
This method is not continuous. The server is not listening to clients always. Can someone help me with this. I need asynchronuous tcp listener that can listen to incoming clients and that too in windows form. Console Server I have.

How to add multiple clients to a server in c#?

My Client Source Code :
public partial class Form1 : Form
{
string serverip = "localHost";
int port = 160;
public Form1()
{
InitializeComponent();
}
private void Submit_Click(object sender, EventArgs e)
{
TcpClient client = new TcpClient(serverip, port);
int byteCount = Encoding.ASCII.GetByteCount(Message.Text);
byte[] sendData = new byte[byteCount];
sendData = Encoding.ASCII.GetBytes(Message.Text);
NetworkStream stream = client.GetStream();
stream.Write(sendData, 0, sendData.Length);
stream.Close();
client.Close();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
My server
class Program
{
static void Main(string[] args)
{
IPAddress ip = Dns.GetHostEntry("localHost").AddressList[0];
TcpListener server = new TcpListener(ip, 160);
TcpClient client = default(TcpClient);
try
{
server.Start();
Console.WriteLine("The server has started successfully");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
Console.ReadLine();
}
while (true)
{
client = server.AcceptTcpClient();
byte[] receivedBuffer = new byte[100];
NetworkStream stream = client.GetStream();
stream.Read(receivedBuffer, 0, receivedBuffer.Length);
StringBuilder msg = new StringBuilder();
foreach (byte b in receivedBuffer)
{
if (b.Equals(59))
{
break;
}
else
{
msg.Append(Convert.ToChar(b).ToString());
}
}
Console.WriteLine(msg.ToString() + msg.Length);
}
}
}
Essentially i want make it so i can have multiple clients on the server sending a message from different ip addresses of course. I have been using c# a year now mostly in school and I am above average at best at it.
First time asking question so sorry if its in wrong format

'Connection refused' connecting through TCP/IP

I want to connect unity app on android with a computer application. I could run it on the network but over internet it is always saying the machine is refusing the connection. I have disabled the firewall of windows and anti-virus but still have problem connecting the server and Android client:
No connection could be made because the target machine actively refused it.
Here is the code:
Server side:
TcpListener tcpListener;
Socket socket;
NetworkStream networkStream;
Thread thread;
string getIpAddress()
{
System.Net.IPHostEntry host;
string localIp = "";
host = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
foreach (System.Net.IPAddress ip in host.AddressList)
{
localIp = ip.ToString();
}
return localIp;
}
public void ReceiveImage()
{
try
{
IPAddress localAddr = IPAddress.Parse("95.171.54.53");
tcpListener = new TcpListener(localAddr, 53100);
tcpListener.Start();
socket = tcpListener.AcceptSocket();
networkStream = new NetworkStream(socket);
pictureBox1.Image = Image.FromStream(networkStream);
if (socket.Connected == true)
{
while (true)
{
tcpListener.Stop();
ReceiveImage();
}
}
}
catch(Exception ex)
{
string Message = ex.Message;
}
}
private void Form1_Load(object sender, EventArgs e)
{
thread = new Thread(new ThreadStart(ReceiveImage));
thread.Start();
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
tcpListener.Stop();
thread.Abort();
}
This is the client side:
// Update is called once per frame
int frameSaveCount = -1;
int FrameCount = -1;
Socket socket;
NetworkStream networkStream;
Thread thread;
MemoryStream memoryStream;
TcpClient tcpClient;
BinaryWriter binaryWriter;
void Update()
{
// ...
if(FrameCount % 10==0)
{
// ...
send(bytes);
}
}
void send(Byte[] bytes)
{
try
{
print(getIpAddress());
tcpClient = new TcpClient("95.171.54.53", 53100);
networkStream = tcpClient.GetStream();
binaryWriter = new BinaryWriter(networkStream);
binaryWriter.Write(bytes);
binaryWriter.Close();
networkStream.Close();
tcpClient.Close();
}
catch (Exception exception)
{
string message = exception.Message;
print(message);
}
}
the machine is refusing the connection
This error has exactly one meaning: nothing was listening at the IP:port you tried to connect to. So, either it was wrong, or your server wasn't started when your client tried to connect.
Image files have precisely nothing to do with it.

How would I constant listen on a port with a GUI?

I am trying to learn TCP server/client interaction. I want to know how I would listen to a port all the time with GUI. Currently I am using this code:
private void Form1_Load(object sender, EventArgs e)
{
CreateServer();
}
void CreateServer()
{
TcpListener tcp = new TcpListener(25565);
tcp.Start();
Thread t = new Thread(() =>
{
while (true)
{
var tcpClient = tcp.AcceptTcpClient();
ThreadPool.QueueUserWorkItem((_) =>
{
Socket s = tcp.AcceptSocket();
console.Invoke((MethodInvoker)delegate { console.Text += "Connection esatblished: " + s.RemoteEndPoint + Environment.NewLine; });
byte[] b = new byte[100];
int k = s.Receive(b);
for (int i = 0; i < k; i++)
{
console.Text += Convert.ToChar(b[i]);
incoming += Convert.ToChar(b[i]);
}
MessageBox.Show(incoming);
console.Invoke((MethodInvoker)delegate { console.Text += incoming + Environment.NewLine; });
list.Invoke((MethodInvoker)delegate { list.Items.Add(incoming); });
ASCIIEncoding asen = new ASCIIEncoding();
s.Send(asen.GetBytes("\n"));
tcpClient.Close();
}, null);
}
});
t.IsBackground = true;
t.Start();
}
Any help would be much appreciateed.
Short answer - run TCP listener in the separate Thread/Task (TPL).
For full working solution you also have to implement dispatching of the any changes to UI form separate thread to main thread using special technique which is depends on Framework you are using, I mean WPF/WinForms/whatever.
Code below works for me fine. Read TODO section before.
TODO:
Add to form Textbox, ListBox, Button, make public:
public System.Windows.Forms.TextBox console;
public System.Windows.Forms.ListBox incommingMessages;
private System.Windows.Forms.Button sendSampleDataButton;
Entry point:
private static Form1 form;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
form = new Form1();
form.Load += OnFormLoad;
Application.Run(form);
}
private static void OnFormLoad(object sender, EventArgs e)
{
CreateServer();
}
Server:
private static void CreateServer()
{
var tcp = new TcpListener(IPAddress.Any, 25565);
tcp.Start();
var listeningThread = new Thread(() =>
{
while (true)
{
var tcpClient = tcp.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(param =>
{
NetworkStream stream = tcpClient.GetStream();
string incomming;
byte[] bytes = new byte[1024];
int i = stream.Read(bytes, 0, bytes.Length);
incomming = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
form.console.Invoke(
(MethodInvoker)delegate
{
form.console.Text += String.Format(
"{0} Connection esatblished: {1}{2}",
DateTime.Now,
tcpClient.Client.RemoteEndPoint,
Environment.NewLine);
});
MessageBox.Show(String.Format("Received: {0}", incomming));
form.incommingMessages.Invoke((MethodInvoker)(() => form.incommingMessages.Items.Add(incomming)));
tcpClient.Close();
}, null);
}
});
listeningThread.IsBackground = true;
listeningThread.Start();
}
Client
private void button1_Click(object sender, EventArgs e)
{
Connect("localhost", "hello localhost " + Guid.NewGuid());
}
static void Connect(String server, String message)
{
try
{
Int32 port = 25565;
TcpClient client = new TcpClient(server, port);
Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
NetworkStream stream = client.GetStream();
// Send the message to the connected TcpServer.
stream.Write(data, 0, data.Length);
stream.Close();
client.Close();
}
catch (ArgumentNullException e)
{
Debug.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
Debug.WriteLine("SocketException: {0}", e);
}
}
Screenshot:
Create a thread, start to listen in it & don't stop the server
void CreateServer()
{
TcpListener tcp = new TcpListener(25565);
tcp.Start();
Thread t = new Thread(()=>
{
while (true)
{
var tcpClient = tcp.AcceptTcpClient();
ThreadPool.QueueUserWorkItem((_) =>
{
//Your server codes handling client's request.
//Don't access UI control directly here
//Use "Invoke" instead.
tcpClient.Close();
},null);
}
});
t.IsBackground = true;
t.Start();
}
You could use the threads approach (as mentioned by other answers) or use asynchronous sockets, which in my opnion is way better. And even better, you can use the async model proposed by SocketAsyncEventArgs.
Async sockets will take benefits from using completion ports.
here is a good example on mdsn: Asynchronous server socket example

Categories