C# TCP connecting to a computer - c#

After some research I've almost managed to get a program to connect to another PC using TCP.
I've made 2 programs :
one to connect and
one to receive which goes on the other computer if that makes sense.
I'm not sure if I use my public IP address to connect but it doesn't work.
I'm not sure if its the program or the wrong IP.
So here is the code for the program that connects.
public static bool IsConnected;
public static NetworkStream Writer;
static void Main(string[] args)
{
Console.Title = "Offline";
TcpClient Connector = new TcpClient();
GetConnection:
Console.WriteLine("Enter server IP :");
string IP = Console.ReadLine();
try
{
Connector.Connect(IP, 2001);
IsConnected = true;
Console.Title = "Online";
Writer = Connector.GetStream();
}
catch
{
Console.WriteLine("Error connecting to target server! Press any key to try again.");
Console.ReadKey();
Console.Clear();
goto GetConnection;
}
Its a console application where I just type in the ip address and it tells me if its connected or not,
It uses port 2001 just like the receiver which the code for that is below.
public static NetworkStream Receiver;
[DllImport("kernel32.dll")]
static void Main(string[] args)
{
FreeConsole();
TcpListener l = new TcpListener (2001);
l.Start();
TcpClient Connection = l.AcceptTcpClient();
Receiver = Connection.GetStream();
}
If anyone has any ideas as to why it doesn't connect its appriciated

I was using the public ip address instead of the ipv4 address

Related

Serial Port not reading - C#

I have a machine where I have to read the data coming through comport. But the comport output is this one link on the picture below:
I have created a program where I was able to intercept the data coming through but it was the "normal" Com Port.
Cable is working normally, when I connect to a printer, it prints normally. What I need to do is get, on my program, the same data that is printed. I sucessfully have done that but not with this different output(image 1). The class I am using the SerialPort class to do this work for me.
SerialPort port = new SerialPort();
My code is working. I am just wondering if for the output(image 1) I have to use a different class. I couldn't find anything related to that, once I search anything related to COM Port or Serial Port, I ended up on the same results, that's why I am here.
Hope I could myself clear.
Thanks
My class:
using System;
using System.IO.Ports;
namespace SerialReader
{
class PortReader
{
static void Main(string[] args)
{
// Get a list of serial port names.
string[] ports = SerialPort.GetPortNames();
Console.WriteLine("The following serial ports were found:");
// Display each port name to the console.
foreach (string port in ports)
{
Console.WriteLine(port);
}
Console.WriteLine("Enter the COM Port: ");
string comport = Console.ReadLine();
var reader = new ArduinoSerialReader(comport);
Console.ReadLine();
}
}
public class ArduinoSerialReader : IDisposable
{
private SerialPort _serialPort;
public ArduinoSerialReader(string portName)
{
_serialPort = new SerialPort(portName);
_serialPort.Open();
_serialPort.DataReceived += serialPort_DataReceived;
}
void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
{
Console.WriteLine(_serialPort.ReadLine());
}
public void Dispose()
{
if (_serialPort != null)
{
_serialPort.Dispose();
}
}
}
}

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.

TcpListener constant error Only one usage of each address

I am trying to use a TcpListener. Every time I try to start the listener I get the error that the Address is already in use. I have looked at netstat and cant see anything on that endpoint(IP Address, Port).
class Program
{
static void Main(string[] args)
{
IPAddress ip = IPAddress.Parse("127.0.0.1");
TcpListener listener = new TcpListener(ip, 58000);
listener.Start();
}
}
When I run that I the error every time.
The error is pretty clear that another process (it's probably because of unfinisted exe of your program) bind the same port which you want to listen. Try to listen different port and see the case;
IPAddress ip = IPAddress.Parse("127.0.0.1");
TcpListener listener = new TcpListener(ip, 58001);
listener.Start();
Also, I strongly suggest you to use TcpView to inspect allocated ports.
You have for sure another process(most probably the same you are trying to run) running in background so you cannot open the port. Try to open and and ensure to close the connections:
public static void Main()
{
TcpListener server=null;
try
{
Int32 port = 58000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// DO ALL YOUR WORK
}
catch(SocketException e)
{
Console.WriteLine(e.ToString());
}
finally
{
// Stop listening for new clients.
server.Stop();
}
}

C# server.AcceptTcpClient and Listbox

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

connect to C# server on EC2 (AWS)

I'm trying to connect to a C# TCP server I'm running on EC2.
But my server's not responding. This is the code that running on the EC2:
static void Main(string[] args)
{
TcpListener serverSocket = new TcpListener(8888);
TcpClient clientSocket = default(TcpClient);
serverSocket.Start();
clientSocket = serverSocket.AcceptTcpClient();
Console.WriteLine("new client connected");
}
And them from my own PC I'm trying to run this code:
static void Main(string[] args)
{
TcpClient clientSocket = new TcpClient();
clientSocket.Connect("35.163.41.3", 8888);
Console.WriteLine("you connected to the server!");
}
This is the security group of my EC2:
What could the problem be?
It could be a number of things. First thing I would check is Windows Firewall on the server to make sure that it is allowing that port.

Categories

Resources