unable to connect to another computer in C# - c#

hello guyz i have made a bare bone program in C# that simply sends a message from server to client.
Now i have successfully tested both programs running on the same machines. However when i attempt to connect 2 different computers on different networks it sends me the unable to connect message.
Here the server code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Net.Sockets;
namespace chat_client_console
{
class Program
{
static TcpListener listener;
static void Main(string[] args)
{
/*
string name = Dns.GetHostName();
IPAddress[] address = Dns.GetHostAddresses(name);
foreach(IPAddress addr in address)
{
Console.WriteLine(addr);
}
Console.WriteLine(address[2].ToString());*/
Console.WriteLine("server");
listener = new TcpListener(IPAddress.Any, 2055);
listener.Start();
Socket soc = listener.AcceptSocket();
Console.WriteLine("Connection successful");
Stream s = new NetworkStream(soc);
StreamReader sr = new StreamReader(s);
StreamWriter sw = new StreamWriter(s);
sw.AutoFlush = true;
sw.WriteLine("A test message");
sw.WriteLine("\n");
Console.WriteLine("Test message delivered. Now ending the program");
/*
string name = Dns.GetHostName();
Console.WriteLine(name);
//IPHostEntry ip = Dns.GetHostEntry(name);
//Console.WriteLine(ip.AddressList[0].ToString());
IPAddress[] adr=Dns.GetHostAddresses(name);
foreach (IPAddress adress in adr)
{
Console.WriteLine(adress);
}
*/
Console.ReadLine();
}
}
}
and here the client code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net.Sockets;
namespace chat_client_console_client
{
class Program
{
static void Main(string[] args)
{
string host_ip_address;
Console.WriteLine("Enter server ip address");
host_ip_address=Console.ReadLine();
string display;
TcpClient client = new TcpClient(host_ip_address, 2055);
Stream s = client.GetStream();
Console.WriteLine("Connection successfully received");
StreamWriter sw = new StreamWriter(s);
StreamReader sr = new StreamReader(s);
sw.AutoFlush = true;
/*while (true)
{
display = sr.ReadLine();
if (display == "")
{
Console.WriteLine("breaking stream");
break;
}
}*/
display = sr.ReadLine();
Console.WriteLine(display);
Console.ReadLine();
}
}
}
now when i enter the 127.0.0.1 in the client program it successfully connects to the server and the message is received.
However when i enter my external ip address in the client program running on another computer i am unable to connect.
Suggestions are required in this matter.
Thank you.

You can use Wireshark in the client computer and look up any tcp packet to make sure the message sent to server.

Related

c# windows forms app /client server /checking client input to do something is not working in

I'm creating a client server app using c# and what it does :
1- the client sends a msg then the server sends it back to the client
2- I want to check what the client send and do some process like if the client send "chrome"
the server checks it and open chrome.exe
I don't know why its not working here on my code:
when the client sends chrome it always shows client disconnected message
also i cant convert it to windows froms app its shows lots of errors
#server code!
using System;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Net;
using System.Text;
namespace consoleTcpServer {
class Program {
class ConnectionHandler {
private Socket client;
private NetworkStream ns;
private StreamReader reader;
private StreamWriter writer;
private static int connections = 0;
//The constructor take the accepted client as argument
public ConnectionHandler(Socket client) {
this.client = client;
}
public void HandleConnection() {
try {
ns = new NetworkStream(client);
reader = new StreamReader(ns);
writer = new StreamWriter(ns);
connections++;
Console.WriteLine("New client accepted: {0} active connections",
connections);
writer.WriteLine("Welcome to my server");
writer.Flush();
string input;
while ((input = reader.ReadLine()).Length != 0) {
if (input.Contains("chrome")) {
System.Diagnostics.Process.Start("chrome.exe", "www.google.com");
} else if (input.Contains("fox")) {
System.Diagnostics.Process.Start("firefox.exe", "www.facebook.com");
}
Console.WriteLine(input);
writer.WriteLine(input);
writer.Flush();
}
// ns.Close();
// client.Close();
connections--;
Console.WriteLine("Client disconnected: {0} active connections", connections);
} catch (Exception) {
connections--;
Console.WriteLine("Client disconnected: {0} active connections",
connections);
}
}
}
static void Main(string[] args) {
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 9050);
server.Bind(localEP);
server.Listen(10);
Console.WriteLine("Waiting for a client");
while (true) {
try {
Socket client = server.Accept();
ConnectionHandler handler = new ConnectionHandler(client);
Thread thread = new Thread(new ThreadStart(handler.HandleConnection));
thread.Start();
} catch (Exception) {
Console.WriteLine("Connection failed ..");
}
//client.Close();
//server.Shutdown();
}
}
}
}
#client code
using System;
using System.Net;
using System.IO;
using System.Net.Sockets;
using System.Threading;
using System.Text;
namespace consoleTcpClient {
class Program {
static void Main(string[] args) {
// Console.WriteLine("Hello World!");
Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9050);
client.Connect(remoteEP);
NetworkStream stream = new NetworkStream(client);
StreamReader reader = new StreamReader(stream);
StreamWriter writer = new StreamWriter(stream);
String input = reader.ReadLine();
Console.WriteLine(input);
String line = null;
while (true) {
Console.Write("Enter Message for Server <Enter to Stop >: ");
line = Console.ReadLine();
//writing for server
writer.WriteLine(line);
writer.Flush();
if (line.Length != 0) {
line = "Echo: " + reader.ReadLine();
Console.WriteLine(line);
}
}
// client.Close();
}
}
}

Permanent receiving of sent XML over TCP

C# Form .Net 4.7
A client app should receive XML data from an external payment machine. The XML is automatically sent after each deposit. It's about receiving it at any time and displaying it in a TextBox.
Sending takes place via TCP
The machine opens the connection to the external system at the specified port
Sends the data
Waits for confirmation on the same connection if necessary
Closes the connection
Since the client has to be able to receive the data at any time, I thought about a listener. But I'm not sure if this approach is the right one. What I did here doesn't work. I wanted to test that with a localhost. There is sure to be a simple solution. But since I'm not a network specialist, I can't find it. Does anyone know how to do it best?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace TCPListener
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
TcpListener Listener = null;
Int32 port = 8080;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
private void button1_Click(object sender, EventArgs e)
{
Listener = new TcpListener(localAddr, port);
byte[] receiveBuffer = new byte[10025];
while (true)
{
int requestCount = 0;
Listener.Start();
MessageBox.Show(" >> Listener Started");
using (var tcpClient = Listener.AcceptTcpClient())
{
MessageBox.Show(" >> Accepted connection from client");
using (var networkStream = tcpClient.GetStream())
{
while (true)
{
try
{
requestCount = requestCount++;
var bytesRead = networkStream.Read(receiveBuffer, 0, (int)tcpClient.ReceiveBufferSize);
if (bytesRead == 0)
{
// Read returns 0 if the client closes the connection
break;
}
string dataFromClient = System.Text.Encoding.ASCII.GetString(receiveBuffer, 0, bytesRead);
XmlDocument xm = new XmlDocument();
xm.LoadXml(string.Format("<root>{0}</root>", dataFromClient));
XmlElement root = xm.DocumentElement;
string rootName = root.FirstChild.Name;
textBox1.Text = (rootName, dataFromClient);
}
catch (Exception ex)
{
MessageBox.Show("ReceivePortMessages: " + ex.ToString());
break;
}
}
}
MessageBox.Show(" >> stopped read loop");
}
Listener.Stop();
}
}
}
}

sending additional client info to server in C#

I have written a client program using c# socket programming which will send a file to the server. Is there any way I can send a client ID (say: 1234) to the server so that the server can recognize different clients? What modification will I have to make in the following code?
// Client
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Text;
namespace FileTransferClient
{
class Program
{
static void Main(string[] args)
{
try
{
string fileName = #"D:\demo.txt";
string p = Path.GetExtension(fileName);
FileInfo f = new FileInfo(fileName);
long s1 = f.Length;
TcpClient tcpClient = new TcpClient("127.0.0.1", 1234);
Console.WriteLine("Connected. Sending file.");
StreamWriter sWriter = new StreamWriter(tcpClient.GetStream());
byte[] bytes = File.ReadAllBytes(fileName);
sWriter.WriteLine(bytes.Length.ToString());
sWriter.Flush();
sWriter.WriteLine(fileName);
sWriter.Flush();
Console.WriteLine("Sending file");
tcpClient.Client.SendFile(fileName);
}
catch (Exception e)
{
Console.Write(e.Message);
}
Console.Read();
}
}
}

C# Chat clients with multiple threads (read+write at the same time)

How do I make the client read from the stream (for messages of other clients sent to the stream) at the same time as being able to write to them?
I tried creating different threads on the client side (did I even do it right?), however I can still only write to the server, without any response. This is what I'm getting right now:
(Server-Client-Client)
Client:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace Klientas
{
class Klientas
{
public static void Write()
{
while (true)
{
TcpClient clientSocket = new TcpClient("localhost", 1000);
string str = Console.ReadLine();
BinaryWriter writer = new BinaryWriter(clientSocket.GetStream());
writer.Write(str);
}
}
public static void Read()
{
while (true)
{
TcpClient clientSocket = new TcpClient("localhost", 1000);
BinaryReader reader = new BinaryReader(clientSocket.GetStream());
Console.WriteLine(reader.ReadString());
}
}
static void Main(string[] args){
Thread ctThread = new Thread(Write);
Thread ctThread2 = new Thread(Read);
ctThread2.Start();
ctThread.Start();
}
}
}
Server:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Net.Sockets;
using System.IO;
namespace MultiServeris
{
class Multiserveris
{
static void Main(string[] args)
{
TcpListener ServerSocket = new TcpListener(1000);
ServerSocket.Start();
Console.WriteLine("Server started.");
while (true)
{
TcpClient clientSocket = ServerSocket.AcceptTcpClient();
handleClient client = new handleClient();
client.startClient(clientSocket);
}
}
}
public class handleClient
{
TcpClient clientSocket;
public void startClient(TcpClient inClientSocket)
{
this.clientSocket = inClientSocket;
Thread ctThread = new Thread(Chat);
ctThread.Start();
}
private void Chat()
{
while (true)
{
BinaryReader reader = new BinaryReader(clientSocket.GetStream());
Console.WriteLine(reader.ReadString());
}
}
}
}
It seems like you do not have any code on the server to send messages to the client. You need to maintain a list of connected clients and make the server send a message to the eligible clients when it receives a message. Also do not make the client a console app. Unlike most projects for a chat client it is actually harder to do it as a console app.
To keep a list of clients you declare a list of TCP Clients like this
static List<TcpClient> clients = new List<TcpClient>();
Then when a client connects you add it to the list
TcpClient clientSocket = ServerSocket.AcceptTcpClient();
clients.Add(clientSocket);
Then when you receive a message you send it to all clients
BinaryReader reader = new BinaryReader(clientSocket.GetStream());
while(true)
{
string message = reader.ReadString();
foreach(var client in clients)
{
//send message to client
}
}
Now remember that in practice you should handle things like disconnects and adding and removing clients from the list should be thread safe (locks and all).
Good starting point for socket client-server communication: demo application and library. Support for reconnecting, sudden client disconnect catch, message broadcasting and many more.

Simple Web Server C#

I need some help with this code:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace HttpEcho
{
class HttpEchoProgram
{
static void Main(string[] args)
{
TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);
server.Start();
Console.WriteLine("Waiting for Client...");
TcpClient newConn = server.AcceptTcpClient();
IPEndPoint iep = (IPEndPoint)(newConn.Client.RemoteEndPoint);
IPAddress add = iep.Address;
int prt = iep.Port;
Console.WriteLine("Connected with a client: {0}: {1} ", add, prt);
NetworkStream stream = newConn.GetStream();
StreamReader sr = new StreamReader(stream);
StreamWriter sw = new StreamWriter(stream);
sw.WriteLine("HTTP/1.1 200 OK");
sw.WriteLine("Content-Type: text/plain");
//sw.WriteLine("Content-Length: size");
sw.WriteLine();
String line = null;
while ((line = sr.ReadLine()).Length != 0)
{
Console.WriteLine(line);
sw.WriteLine(line);
sw.Flush();
}
newConn.Close();
server.Stop();
}
}
}
I want to modify this code so it can work as a Simple Web Server that it fetches requested page in the local file system and returns it to the browser.
You can save yourself a few thousand lines of code by starting with a HttpListener instead. http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx

Categories

Resources