C# server.AcceptTcpClient and Listbox - c#

I'm writing a simple TCP-Connection software.
Firstly, I wrote the server in a ConsoleApp and it workes quite well.
Now I wanted to port it to a form application, but when a client connects, it does not add a new entry in my ListBox, on the Console it workes well.
I tried to write in the Load function as well as writing it in a separate Thread.
Both don't work.
In the Console it worked like this, and the Console wrote "User connected":
static void Main(string[] args)
{
const int PORT = 14758;
TcpListener server = new TcpListener(IPAddress.Any, PORT);
try
{
server.Start();
Console.WriteLine("Server started");
} catch (Exception Ex)
{
Console.WriteLine("Error", Ex);
}
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("User connected");
Now in my form App it does not work like this:
public frmMainServer()
{
InitializeComponent();
Thread serverStart = new Thread(new ThreadStart(start_Server));
serverStart.Start();
serverStart.Join();
TcpClient client = server.AcceptTcpClient();
addItem("User connected");
}
As said before, I tried to write the last 2 lines in the Thread, too, but it didn't help.
I actually think I CAN connect to the server, so why does it not add the line?
addItem function:
private void addItem(string item)
{
_items.Add(item);
listStatus.DataSource = _items;
}

Related

Communication between STM32 and C# via ESP8266

I'm now trying to connect STM32F429 to C# desktop application with ESP8266(in STA mode). I want ESP8266 to be a client and C# to be a Server. However ESP8266 remains failing to find my PC in the same LAN.
Now I have succeeded to use AT command to connect ESP8266 to my Router AP. And I used XAMPP to open a gate on my PC whose address is 192.168.1.11:80, then use the following command (AT+CIPSTART=\"TCP\",\"192.168.1.11\",80") to successfully connect ESP8266 to it(It returned OK to my STM32F429).
Then I wanna replace XAMPP with my C# code to open a TCP server. But I couldn't make it!
As for the C# Code, I have successfully build a connection between two C# programs (The IP Address is 192.168.1.11:80 which is the same as the one mentioned above).But when I tried to use ESP8266 to connect to the same IP and Port, it failed.
I suspected that there might be some wrong conceptions I have got about opening a TCP Listener on certain port in my LAN... I don't know...
The following is my C# code. (The code of STM32 is just a basic Usart code which I won't present here.)
// Code for Server
namespace Tcp_Server
{
public partial class Form1 : Form
{
private TcpListener myListener;
private TcpClient newClient;
public BinaryReader br;
public BinaryWriter bw;
public Form1()
{
InitializeComponent();
Thread myThread = new Thread(ServerA);
myThread.Start();
}
private void ServerA()
{
IPAddress SvrIP = new IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address); // Get the virtual IP of my PC.
this.Invoke(new AddToTextbox_dg(AddToTextbox), new object[] { tb_ServerStatus, ip.ToString() });
myListener = new TcpListener(ip, 80); //construct a Tcp Listener.
myListener.Start(); //Tcp Listener start
newClient = myListener.AcceptTcpClient();// Searching for a client...
this.Invoke(new AddToTextbox_dg(AddToTextbox), new object[] { tb_ServerStatus, "Connect Successfully" });
while (true)
{
try
{
NetworkStream clientStream = newClient.GetStream();
br = new BinaryReader(clientStream);
string receive = null;
receive = br.ReadString();//读取
this.Invoke(new AddToTextbox_dg(AddToTextbox), new object[] { tb_ServerStatus, receive });
}
catch
{
MessageBox.Show("Receving failed...");
}
}
}
// Code for client
namespace Client
{
public partial class Form1 : Form
{
private TcpClient client;
public BinaryReader br;
public BinaryWriter bw;
public Form1()
{
InitializeComponent();
Thread myThread = new Thread(ClientA);
myThread.Start();
}
private void ClientA()
{
IPAddress ip = new IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address); // Get the virtual IP of my PC.
client = new TcpClient(ip.ToString(), 80);
this.Invoke(new AddToTextbox_dg(AddToTextbox), new object[] { tb_ServerStatus, "Connect to Server Successfully!" });
while (true)
{
try
{
NetworkStream clientStream = client.GetStream();
br = new BinaryReader(clientStream);
string receive = null;
receive = br.ReadString();
}
catch
{
MessageBox.Show("Receving failed...");
}
}
}
private void AddToTextbox(TextBox txt, String s)
{
txt.Text += s;
}
private delegate void AddToTextbox_dg(TextBox txt, String s);
private void btn_send_Click(object sender, EventArgs e)
{
NetworkStream clientStream = client.GetStream();
bw = new BinaryWriter(clientStream);
bw.Write(message.Text);
}
}
}
Could somebody please help me with this problem ?
I wonder why I cannot connect ESP8266 to the TcpListener I built on my PC with C#.
What did my PC do when receiving the command:
myListener = new TcpListener(ip, 80);
This project I'm doing is about to transmit the image data I got with Stm32F429 and OV7725 to my PC through ESP8266. I know Usart will be too slow to do that, but now I'm just trying to build the connection. Is there any suggestion you guys could give me about this?
First, make sure no other application on your pc is listening to port 80. if so, you have to change it.
Second, try setting the ip of the TCPListener to local host "127.0.0.1". you will be able to reach this server by connecting to the ip of your PC.
I have checked the used IP in command window as below:
Command Window for checking IP usage
And I remain the IP address which ESP8266 will try to access to be 192.168.1.11:1900 which is the virtual IP of my PC in the LAN as below:
Address ESP8266 try to access
And change the IP C# will try to create a TCPListener on:
C# code
Is this what you mean? Thank you.

Socket on a Thread stops processing and locks the UI

I have a standalone test application developed in c# (4.5).
The application is primarily meant for sending some data to COM ports. The application accepts the data through the UI and the corresponding data is sent to respective COM ports.
For eg: Data from text box 1 goes to COM 1 on pressing a button, Data from Textbox 2 goes to COM 2 on pressing a different button etc.
Later I had to add a functionailty where a different set of data has to be accepted via Windows sockets and has to be sent to a different COM port other than above. This listening socket could receive data from multiple sources. If the listening socket receives back to back socket data, the application is expected to queue the data and process the data on a First come first serve bases.
Hence I created a synchronous socket to receive data. If the server receives data from 2 sources, it processes the data from source 1 and sends the completion status to source 1 and then takes the data from source 2,processes it and informs the status and this goes on. The socket is created on a thread so that it could receive and process data independently from the UI.
The application was meeting its objective as most of the communication was through sockets and people were not really using the UI for entering data.
Recently, as people started UI, i noticed a completely new issue. When someone tries to enters a data on to UI while the socket data is in process, it stops the socket data processing. When I press ctrl+Alt+Del on the host, it resumes the processing of the socket data.
I could not identify my mistake here. Also, I looked over to the Backgroundworkder class but I am not sure if that would allow the sockets commands to be processed in a synchronous way.
Please treat me as a newbie as I am still learning and complex suggestions might be hard to digest.
public partial class frm_bot : Form
{
public frm_bot()
{
StartServer();
}
private void frm_bot_Load(object sender, EventArgs e)
{
try
{
myThread = new System.Threading.Thread(new System.Threading.ThreadStart(OnClientConnect));
myThread.IsBackground = true;
myThread.Start();
}
catch (Exception ex)
{
showErrorMsg(ex.Message);
}//catch
}
public void StartServer()
{
InitializeComponent();
System.Net.IPAddress localIPAddress = System.Net.IPAddress.Parse(GetlocalIp());
IPEndPoint ipLocal = new IPEndPoint(localIPAddress, 8089);
_listener = new TcpListener(ipLocal);
}
private void OnClientConnect()
{
try
{
_listener.Start();
TcpClient clientSocket = default(TcpClient);
clientSocket = _listener.AcceptTcpClient();
_clientSocket = clientSocket;
ReadCallback();
}
catch (Exception se)
{
MessageBox.Show("Could not bind to Port 8089! Please close all Applications that uses Port 8089");
}
}
public void ReadCallback()
{
try
{
using (StreamReader sr = new StreamReader(_clientSocket.GetStream()))
using (StreamWriter sw = new StreamWriter(_clientSocket.GetStream()))
{
sw.AutoFlush = true;
char[] c = null;
while (sr.Peek() >= 0)
{
c = new char[25];
sr.Read(c, 0, c.Length);
Console.WriteLine(c);
}
string d = new string(c);
string[] cmddata = d.Split('\0');
string dataFromClient = cmddata[0];
if (dataFromClient.Length == 0)
{
Console.WriteLine("Client sent empty string!");
}
else
{
ProcessSocketData(dataFromClient);
sw.Write("Done");
}
sw.Close();
}
OnClientConnect();
}
catch (Exception ex)
{
OnClientConnect();
return;
}
}
public void ProcessSocketData(string sockdata)
{
try
{
// Socket data is processed here.
}
catch (Exception ex)
{
MessageBox.Show("Exception on ProcessSocketData: " + ex.Message);
return;
}
}
}

Can't receive Broadcasts in WinRT

I'm trying to receive a broadcast via DatagramSockets in WinRT/C#, but I just don't receive a packet.
To be more specific, this is my code:
public sealed partial class MainPage : Page
{
public MainPage(){
this.InitializeComponent();
}
private DatagramSocket listener;
async private void Loaded(object sender, RoutedEventArgs e) {
listener = new DatagramSocket();
listener.MessageReceived += MessageReceived;
await listener.BindServiceNameAsync("50011");
}
private void MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args) {
txtText.Text = "Win :D:D:D:D:D:D:D"; //Breakpoint here
}
}
The program never reaches the breakpoint.
I've set all the correct rights/permissions in the appxmanifest.
The program which sends the broadcast is the following one:
static void Main(string[] args) {
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1);
IPEndPoint iep = new IPEndPoint(IPAddress.Broadcast, 50011);
string hostname = Dns.GetHostName();
byte[] data = new byte[1];
data[0] = 129;
while (true) {
sock.SendTo(data, iep);
Console.WriteLine("Daten gesendet: {0}", data[0]);
Thread.Sleep(1000);
}
}
I know this program works, because I tested it with another little C# programm on the same PC (but not with WinRT functionality, just normal C#). Also it can't be a Firewall- or Routing Problem, because it, as I just mentioned, already worked with a normal C# program (but I already tried turning the firewall off).
I'm currently trying it on a Wifi-Network using Windows 8.1 and have x64 Processor.
Am I missing something? Is it even possible?
I hope somebody of you can help me
(PS: I know it's pretty similar to this post: Can't Receive UDP Windows RT but there hasen't been progress for more than a year so ...)
I solved it.
You just have to send the broadcasts from a different device.
However it doesn't like broadcasts sent from the same device ....

Console App wont stay open, after setting isBackground = true on thread

so I have created a server which needs to listen for clients to connect and in the constructor of my server class I have:
class Server
{
private Thread listenerThread;
private TcpListener listener;
public Server()
{
this.listener = new TcpListener(IPAddress.Any, 5000);
listenerThread = new Thread(ListenMethod) { IsBackground = true };
listenerThread.Start();
}
private void ListenMethod()
{
listener.Start();
while (true)
{
TcpClient client = listener.AcceptTcpClient();
}
}
}
but when I created the instance of server in my main like so:
class Program
{
static void Main(string[] args)
{
Server s = new Server();
}
}
The server should stay open cause of the ListenMethod running and the while loop, yet the program seems to complete the constructor and closes the program.
Any ideas?
Thanks :)
Background threads will not keep a console application alive, as is their purpose. The Server class instance is also going out of scope because it isn't used by anything; in a Release build of this application it might not even be compiled into the application and optimised away. You need to do something like this:
static void Main(string[] args)
{
Server server = new Server();
Console.Write("The server is running. Press any key to stop the server.");
Console.ReadKey();
server.Stop();
}
It doesn't look like you are instantiating your listner instance, before you call Start(), so the code is probably crashing on listener.Start() due to a NullReferenceException
I would expect something like this:
private void ListenMethod()
{
listener = new TcpListener();
listener.Start();
while (true)
{
TcpClient client = listener.AcceptTcpClient();
}
}

how to setup a tcplistener in windows services c#

Iam beginner to windows services , i have a console application to transfer files between client and server . Now i would like to turn my server application into windows services for listening multiple clients . I placed my console application code inside onstart() . After deploying the windows services not working or listening . Any IQ's...
Here is a complete article on TCP listener in windows service. It's quite old though but may be it helps.
hi i know this question is a long-standing one, and i checked many articles on stackoverflow or other sites, but there is no one make me satisfied. the most headache point is: it is a windows service, the while loop of listener should NOT be blocked when the service startup.
finally i made up a solution by myself, maybe maybe it is not system friendly, but it is quite simple and works fine ( I opened 3 telnet to this server concurrently, and it works as i wish) :-)
here is the code:
`protected override void OnStart(string[] args)
{
tcpServerStart();
}
private void tcpServerStart()
{
try
{
IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
//port 5555, or any port number you want
listener = new TcpListener(ipAddress, 5555);
listener.Start();
var whileThread = new Thread(() =>
{
while (true)
{
// in order to avoid while loop turn into an infinite loop,
// we have to use AcceptTcpClient() to block it.
TcpClient client = listener.AcceptTcpClient();
// for each connection we just fork a thread to handle it.
var childThread = new Thread(() =>
{
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream(); // not blocking call
StreamReader streamreader = new StreamReader(client.GetStream(), Encoding.ASCII);
string line = null;
// below while loop is your logic code, change it to your needs.
// defined "<EOF>" as mine quit message
while ((line = streamreader.ReadLine()) != "<EOF>")
{
// WriteToFile is a function of mineto log system status
WriteToFile(line);
}
stream.Close();
client.Close();
});
childThread.Start();
} // end of while(true) loop
});
whileThread.Start();
}
catch (Exception e)
{
}
} '
this server open thread else never running service
protected override void OnStart(string[] args)
{
TcpServer server=new TcpServer();
server.Start();
}
class TcpServer
{
// clase prar crear un listener
private TcpListener server;
private bool isRunning;
private int port = 13000;
public void Start()
{
// client found.
// create a thread to handle communication
Thread tServer = new Thread(new ParameterizedThreadStart(StartThread));
tServer.Start();
}
public void StartThread(object o)
{
//iniciar configuraciones
Configuracion.init();
// crear un nuevo servidor
server = new TcpListener(IPAddress.Any, port);
//inicializar el servidor
server.Start();
//variable para indicar queesta corriendo el server
isRunning = true;
LoopClients();//thread
}}
public void LoopClients()
{
while (isRunning)
{
// wait for client connection
TcpClient newClient = server.AcceptTcpClient();
// client found.
// create a thread to handle communication
Thread t = new Thread(new ParameterizedThreadStart(HandleClient));
t.Start(newClient);
}
}

Categories

Resources