Simple sending .txt file from one computer to another via TCP/IP - c#

There are two C# projects: one project is for the client, the other one is for the server. First step is to run the server , then to choose a target folder, after that to run the client project, to choose some text.txt to send to the server's target folder.
Only client can send files to the server
Demo:
1.choosing file target 2.client sends
+------------+
| tar folder | <---------------- text.txt
+------------+
My problem: there isn't compile errors or syntax errors in both projects, the only problem is that the server doesn't receives the .txt file.
Client:
First I designed a form for the client such as:
And placed an OpenFileDialog from the ToolBox-> Dialogs-> OpenFileDialog control.
Full code:
namespace SFileTransfer
{
public partial class Form1 : Form
{
string n;
byte[] b1;
OpenFileDialog op;
private void button1_Click(object sender, EventArgs e) //browse btn
{
op = new OpenFileDialog();
if (op.ShowDialog() == DialogResult.OK)
{
string t = textBox1.Text;
t = op.FileName;
FileInfo fi = new FileInfo(textBox1.Text = op.FileName);
n = fi.Name + "." + fi.Length;
TcpClient client = new TcpClient("127.0.0.1", 8100);//"127.0.0.1", 5055
StreamWriter sw = new StreamWriter(client.GetStream());
sw.WriteLine(n);
sw.Flush();
// label2.Text = "File Transferred....";
}
}
private void button2_Click(object sender, EventArgs e) //send btn
{
TcpClient client = new TcpClient("127.0.0.1", 8100);//5050
Stream s = client.GetStream();
b1 = File.ReadAllBytes(op.FileName);
s.Write(b1, 0, b1.Length);
client.Close();
// label2.Text = "File Transferred....";
}
}
}
Server:
Created and designed a Form for Server like:
Then Placed a folderBrowserDialog from the ToolBox->Dialogs-> folderBrowserDialog.
Full code:
namespace SFileTransferServer
{
public partial class Form1 : Form
{
string rd;
byte[] b1;
string v;
int m=1;
TcpListener list;
TcpClient client;
Int32 port = 8100;//5050
Int32 port1 = 8100;//5055
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
private void button1_Click(object sender, EventArgs e) //browse button
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = folderBrowserDialog1.SelectedPath;
list = new TcpListener(localAddr, port1);
list.Start();
client = list.AcceptTcpClient();
MessageBox.Show("ggggggg" + m.ToString());
Stream s = client.GetStream();
b1 = new byte[m];
s.Read(b1, 0, b1.Length);
MessageBox.Show(textBox1.Text);
File.WriteAllBytes(textBox1.Text+ "\\" + rd.Substring(0, rd.LastIndexOf('.')), b1);
list.Stop();
client.Close();
label1.Text = "File Received......";
}
}
private void Form2_Load(object sender, EventArgs e)
{
TcpListener list = new TcpListener(localAddr, port);
list.Start();
TcpClient client = list.AcceptTcpClient();
MessageBox.Show("Client trying to connect");
StreamReader sr = new StreamReader(client.GetStream());
rd = sr.ReadLine();
v = rd.Substring(rd.LastIndexOf('.') + 1);
m = int.Parse(v);
list.Stop();
client.Close();
}
}
}
Based on this page

I'm assuming you are a new coder because I'm seeing a lot of inefficient code.
On the Client App: Don't redeclare the TcpClient, instead declare it in the global scope and just reuse it.
Then On the server side: Always use the correct datatype IF AT ALL possible
Int16 port = 8100;
//same as
int port = 8100;
Then on to the question: First you are only reading a single byte from the received data
int m=1;
byte[] b1 = new byte[m];
s.Read(b1, 0, b1.Length);
//Then if you know the length of the byte, why do the computation of b1.Length, just use
s.Read(b1, 0, 1);
I see now you are also opeing the connection on the Load event. But that variable is not in the global scope so you are essentially creating a variable in the Load event then after the Load event finishes, sending it to the garbage collection and then declaring a variable with the same name in the button click event.
So try declaring the TcpListener object in the global scope then assign it in the load event and start listening.
Now the AcceptTcpClient() method is a blocking method so it will block your thead until it receives a connection attempt at which point it will return the client object. So try to use this instead:
https://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener.accepttcpclient(v=vs.110).aspx
using System.Threading;
TcpClient client;
TcpListener server = new TcpListener("127.0.0.1",8100)
Thread incoming_connection = new Thread(ic);
incoming_connection.Start();
private void ic() {
client = server.AcceptTcpClient();
Stream s = client.GetStream();
//And then all the other code
}
Or you can use the Pending method as suggested by MSDN (on the ref page).
EDIT: using threading like this is 'not safe', so if you don't understand threading go read up on it first, this post doesn't cover how to use multi-threading.

Related

c# - networkstream read and write

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.

I have a server application that gets data exactly half the time. Why/how does this happen and how do I fix it?

So my server and chat client are made from 2 different C# TCP tutorials.You may recognize 1 if not both of them and I have made my own modifications to them to fit my own style. When I tried both they worked perfectly fine with 0 loss, but my version has exactly a 50% loss rate.
For instance:
1. A client connects: Data received
2. A client sends text: No Data
3. A client sends text: Data received
4. A client sends text: No Data
The server code is as follows:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Threading;
using System.Net;
namespace WindowsFormsApplication2
{
class Server
{
private TcpListener tcpListener;
private Thread listenThread;
public Hashtable clientsList = new Hashtable();
private System.Windows.Forms.TextBox output;
private delegate void ObjectDelegate(String text);
private ObjectDelegate del;
public Server(System.Windows.Forms.TextBox setOut)
{
this.tcpListener = new TcpListener(IPAddress.Any, 8888);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.IsBackground = true;
this.listenThread.Start();
output = setOut;
del = new ObjectDelegate(outputTextToServer);
}
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
addClient(client);
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.IsBackground = true;
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
String text = getData(clientStream);
del.Invoke(text); //Used for Cross Threading & sending text to server output
//if filter(text)
sendMessage(tcpClient);
//System.Diagnostics.Debug.WriteLine(text); //Spit it out in the console
}
tcpClient.Close();
}
private void outputTextToServer(String text)
{
if (output.InvokeRequired)
{
// we then create the delegate again
// if you've made it global then you won't need to do this
ObjectDelegate method = new ObjectDelegate(outputTextToServer);
// we then simply invoke it and return
output.Invoke(method, text);
return;
}
output.AppendText(Environment.NewLine + " >> " + text);
}
private String getData(NetworkStream stream)
{
int newData;
byte[] message = new byte[4096];
ASCIIEncoding encoder = new ASCIIEncoding();
newData = stream.Read(message, 0, 4096);
String text = encoder.GetString(message, 0, newData); //Translate it into text
text = text.Substring(0, text.IndexOf("$")); //Here comes the money
return text;
}
private void addClient(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
String dataFromClient = getData(clientStream);
if (clientsList.Contains(dataFromClient))
{
Console.WriteLine(dataFromClient + " Tried to join chat room, but " + dataFromClient + " is already in use");
//broadcast("A doppleganger of " + dataFromClient + " has attempted to join!", dataFromClient, false);
}
else
{
clientsList.Add(dataFromClient, tcpClient);
//broadcast(dataFromClient + " Joined ", dataFromClient, false);
del.Invoke(dataFromClient + " Joined chat room ");
//handleClinet client = new handleClinet();
//client.startClient(clientSocket, dataFromClient, clientsList);
}
}
private Boolean connectionAlive(NetworkStream stream)
{
byte[] message = new byte[4096];
int bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = stream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
return false;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
//clientsList.Remove
return false;
}
return true;
}
private void sendMessage(TcpClient client)
{
NetworkStream clientStream = client.GetStream();
ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("Hello Client!");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
}
}
}
And here's my client code
using System;
using System.Windows.Forms;
using System.Text;
using System.Net.Sockets;
using System.Threading;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public delegate void newDelegate();
public newDelegate myDelegate;
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();
NetworkStream serverStream = default(NetworkStream);
string readData = null;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
newMsg();
}
private void newMsg()
{
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textBox2.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
textBox2.Text = "";
}
private void button2_Click(object sender, EventArgs e)
{
readData = "Connecting to Chat Server ...";
msg();
clientSocket.Connect(txtIP.Text, int.Parse(txtPort.Text));
serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(txtName.Text + "$");
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
myDelegate = new newDelegate(disconnect);
Thread ctThread = new Thread(getMessage);
ctThread.IsBackground = true;
ctThread.Start();
button2.Enabled = false;
}
private void getMessage()
{
while (true)
{
serverStream = clientSocket.GetStream();
int buffSize = 0;
byte[] inStream = new byte[clientSocket.ReceiveBufferSize];
buffSize = clientSocket.ReceiveBufferSize;
try
{
serverStream.Read(inStream, 0, buffSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
readData = "" + returndata;
msg();
}
catch
{
Invoke(myDelegate);
return;
}
}
}
private void disconnect()
{
button2.Enabled = true;
}
private void msg()
{
if (this.InvokeRequired)
this.Invoke(new MethodInvoker(msg));
else
textBox1.AppendText(Environment.NewLine + " >> " + readData);
//textBox1.Text = textBox1.Text + Environment.NewLine + " >> " + readData;
}
private void textBox2_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
newMsg();
}
}
private void cmdHost_Click(object sender, EventArgs e)
{
Server serv = new Server(txtLog);
}
}
}
This code is obviously a work in progress and sorry in advance for messiness. Any other suggestions to the code are also welcome.
Okay, this is starting to get a bit long.
There's multiple errors in your code. Starting with the server code:
As Damien noted, you're trying to read each "message" twice - first in HandleClientComm, then again in getData. The stream no longer has the original data, so you're just throwing one of the reads away completely (thus the suspicious 50% "packet" loss)
Later, in getData, you discard all the data in the stream after the first $. While this is obviously an attempt at handling message framing (since TCP is a stream-based protocol, not a message-based protocol), it's a silly one - you're throwing the data away. The reason this didn't show in your testing is that 1) Windows treats local TCP very differently from remote TCP, 2) You'd need to be actually able to send two messages fast enough to make them "blend" together in the stream. That means either sending two messages in about 200ms (default TCP buffering) or blocking on reads.
You keep Flushing the network stream. This doesn't actually do anything, and even if it did, you wouldn't want to do that.
connectionAlive reads from the shared socket - this is always a bad idea. Never have more than one reader - multiple readers don't work with stream-based protocols. It doesn't seem you're using it in your sample code, but beware of trying to.
The commented out clientList.Remove would of course be a cross-thread access of a shared field. If you want to do it like this, you'll have to ensure the concurrent access is safe - either by using ConcurrentDictionary instead of HashSet, or by locking around each write and read of clientList.
You're expecting to get the whole message in one Read. That may be fine for a simple chat client, but it's bad TCP anyway - you need to read until you find your message terminator. If I send a message big enough, your code will just drop dead on text.IndexOf("$").
There's a lot of "style" issues as well, although this isn't code review, so let me just list some: using ancient technology, synchronous sockets for the server, mixing multi-threaded code with GUI at will. This is mostly about maintainability and performance, though - not correctness.
Now, the client is a bit simpler:
Again, don't Flush the network stream.
Don't use background threads if you don't have to. Simply make sure to terminate the connections etc. properly.
Disconnect should actually disconnect. It's not that hard, just close the TcpClient.
What is readData = "" + returndata supposed to do? That's just silly.
You're ignoring the return value of Read. This means that you have no idea how many bytes of data you read - which means your returnData string actually contains the message followed by a few thousand \0 characters. The only reason you don't see them in output is because most of Windows uses \0 as the string terminator ("it made sense at the time"). .NET doesn't.
Again, the Read expects the whole message at once. Unlike the server, this isn't going to crash the client, but your code will behave differently (e.g. an extra \r\n >> even though it's not a separate message.
The style issues from the server also apply here.
As a side-note, I've recently made a simplified networking sample that handles a simple chat client-server system using more modern technologies - using await-based asynchronous I/O instead of multi-threading, for example. It's not production-ready code, but it should show the ideas and intent quite clearly (I also recommend having a look at the first sample, "HTTP-like TCP communication"). You can find the full source code here - Networking Part 2.

WebApplication communication with a Windows Application via Socket

I have a problem on the Socket communication between a computer and the server. What happens is that I establish communication via socket only if I click on a particular button. In the first communication, everything happens perfectly. If I click again, the code is not executed. I put a breakpoint to see what is happening, and saw that occurs the following error when I try to connect to the server
Cannot access a disposed object. Object name: 'System.Net.Sockets.TcpClient'.
So, to work again, I close the client app and open again, and then works normally.
What I Want
I have a web application that has to work just on FireFox. I have a printer that I need to access him through DLL, so I made a client app that conects with this Web Application via Socket. I pass some parameter via stream and recover these parameter in client app and then print.
In my Web Application Code
public void btnImprimeBematech_Venda()
{
Utilidade.QuebraToken tk = new Utilidade.QuebraToken();
int Credenciada = Convert.ToInt32(tk.CarregaToken(1, HttpContext.Current.Request.Cookies["token"].Value));
TcpListener serverSocket = new TcpListener(8852);
int requestCount = 0;
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
while (true)
{
clientSocket = serverSocket.AcceptTcpClient();
requestCount = 0;
while (clientSocket.Connected == true)
{
try
{
requestCount = requestCount + 1;
NetworkStream networkStream = clientSocket.GetStream();
string serverResponse = Request.QueryString["id"].ToString() + ";" + Credenciada.ToString() + ".";
Byte[] sendBytes = Encoding.ASCII.GetBytes(serverResponse);
networkStream.Write(sendBytes, 0, sendBytes.Length);
networkStream.Flush();
}
catch (Exception ex)
{
}
}
}
clientSocket.Close();
serverSocket.Stop();
}
I pass via stream a string, and recover in the client app.
Client app Code
`System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient();`
private void Form1_Load(object sender, EventArgs e)
{
clientSocket.Connect("server_ip", 8852);
this.imprimir();
}
private void button3_click(object sender, EventArgs e)
{
if (clientSocket.Connected == false)
clientSocket.Connect("server_ip", 8852);
this.imprimir();
}
protected void imprimir()
{
NetworkStream serverStream = clientSocket.GetStream();
byte[] inStream = new byte[10025];
serverStream.Read(inStream, 0, (int)clientSocket.ReceiveBufferSize);
string returndata = System.Text.Encoding.ASCII.GetString(inStream);
int ponto = returndata.IndexOf('.');
returndata = returndata.Substring(0, ponto);
string[] quebraretorno = returndata.Split(';');
ServiceReference1.bematechSoapClient bema = new ServiceReference1.bematechSoapClient();
string r = bema.InformacoesImovelBematech(quebraretorno[0], quebraretorno[1]);
int retorno = -1;
retorno = IniciaPorta("COM7");
if (retorno == 1)
{
ConfiguraModeloImpressora(7);
BematechTX(r);
AcionaGuilhotina(1);
FechaPorta();
}
clientSocket.Close();
}
I need that everytime that my user click on a specific button on my Web Application, call my btnImprimeBematech_Venda() and then talk to my Client App to print. Nowadays I need to close the Client App and open again everytime that my user click on my button to print.
I don't know so much about Thread but maybe I need to use that. I don't know.
Someone can help me ?
I think your problem is the Close() call at the end of your client app. Close will release all resources associated with the socket which explains your dispose exception. Try using Shutdown followed by Disconnect(true) which should allow your socket to be reused. See msdn docs here.
Alternatively you could keep the close, and create a new socket every time you connect.

issue with multiple clients and getting a specific stream

I have a simple multithreaded C# server and client. When just one client is connected I can interact with it fine, but when two or more are connected, it seems I am using the last NetworkStream. What I'd like to be able to do is give an input command that specifies the stream to read and write to. So, for example, the first client is "Client 1" and the second client is "Client 2." I'd just type "Client 2" into my command textbox and it will get the stream for the second client.
The problem is, I don't know how to assign the text to the clients. Here is the relevant code from the server:
private void ClientThread(Object client)
{
NetworkStream networkStream = ((TcpClient)client).GetStream();
Dictionary<int, NetworkStream> myClients = new Dictionary<int, NetworkStream>(); // This didn't work.
myClients.Add(counter, ((TcpClient)client).GetStream()); // Wouldn't write.
counter = counter + 1;
streamReader = new StreamReader(networkStream);
streamWriter = new StreamWriter(networkStream);
strInput = new StringBuilder();
while (true)
{
try
{
strInput.Append(streamReader.ReadLine());
strInput.Append("\r\n");
}
catch (Exception error)
{
break;
}
Application.DoEvents();
DisplayMessage(strInput.ToString());
strInput.Remove(0, strInput.Length);
}
}
private void textBox2_KeyDown(object sender, KeyEventArgs e)
{
try
{
if (e.KeyCode == Keys.Enter)
{
//ListView.SelectedListViewItemCollection stuff = listView1.SelectedItems;
//ip is displayed in listView1, if I could also bind the stream for the ip
//to it and select it, that would be cool.
{
strInput.Append(textBox2.Text.ToString());
streamWriter.WriteLine(strInput);
streamWriter.Flush();
strInput.Remove(0, strInput.Length);
if (textBox2.Text == "cls") textBox1.Text = "";
textBox2.Text = "";
}
}
}
catch (Exception error) { }
}
So, how can I do this?
NetworkStream networkStream = myClients[2];
using(streamWriter = new StreamWriter(networkStream))
{
streamWriter.WriteLine("hello client 2"); // send something to Client 2
}
networkStream = myClients[4];
using(streamWriter = new StreamWriter(networkStream))
{
streamWriter.WriteLine("hello client 4"); // send something to Client 4
}
You are obviously storing all your client streams into a dictionary. Just load that stream into a StreamWriter and send your data.
Make your dictionary myClients class field and then just get your currently active stream like above.

Connecting to an IRC server using C#

I've been trying my hand at a minimalistic IRC bot, but I can never get a connection to work.
I'm doing this via a TcpClient object, which I've seen used in other such projects and those reportedly work.
Here's the code.
private string server = "irc.freenode.net";
private int port = 6667;
private string nick = "testingsharpbot";
private string channel = "testblablabla";
private TcpClient irc;
public ConfigForm() {
InitializeComponent();
}
private void ConnectButton_Click(object sender, EventArgs e) {
this.irc = new TcpClient(this.server, this.port);
using(NetworkStream stream = irc.GetStream()){
using(StreamReader sr = new StreamReader(stream)) {
using(StreamWriter sw = new StreamWriter(stream) {NewLine = "\r\n", AutoFlush = true}) {
sw.WriteLine("NICK " + this.nick);
sw.WriteLine("JOIN " + this.channel);
}
}
}
}
So I wait a bit and then do a /whois on the nickname, but I always get the same reply: user does not exist.
As far as I'm aware, the TcpClient makes the connection and I can then use the NetWorkStream instance to read and write to that connection.
What else do I need to do?
At first, I suggest you taking a look in the appropiate RFC:
http://www.faqs.org/rfcs/rfc2812.html
Look at Connection Registration. You need to follow this steps to get a connection:
Pass message
Nick message
User message
You're missing the USER command.

Categories