C# Sockets: client is not connecting to server in seprate computers - c#

Im new to c# sockets programing and im working on a little project of a server that sends strings for some clients. I made it by modifing MSDN's Synchronous Server and client Socket Example.
When I run the server and the clients on the same computer,they work fine, but when I run the server on a computer and the client on another computer, a socket exception shows on the client(both computers are at the same network).
Now im not sure what to do: port forwarding? change the code?
server code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace textweb
{
class Program
{
static int counter = 0;
static Socket[] _socket = new Socket[2];
static void Main(string[] args)
{
byte[] bytes = new Byte[1024];
//running the server on the local host
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
Console.WriteLine(ipHostInfo.HostName);
IPAddress ipAddress = ipHostInfo.AddressList[0];
Console.WriteLine(ipAddress);
TcpListener listener = new TcpListener(ipAddress, /*MyPort*/);
try
{
listener.Start(10);
Console.WriteLine("Waiting for a connection...");
while (counter < 2)
{
while (!listener.Pending()) { }
while (listener.Pending())
{
_socket[counter] = listener.AcceptSocket();
counter++;
}
}
bool _continue = true;
while (_continue)
{
string m = Console.ReadLine();
byte[] msg = Encoding.ASCII.GetBytes(m);
foreach (Socket soc in _socket)
{
soc.Send(msg);
if (m == "exit")
{
soc.Shutdown(SocketShutdown.Both);
soc.Close();
_continue = false;
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress any key to continue...");
Console.ReadKey();
}
}
}
client code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace textclient
{
class Program
{
static void Main(string[] args)
{
byte[] bytes = new byte[1024];
try {
IPHostEntry ipHostInfo = Dns.GetHostByName(/*server's ip*/);
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint remoteEP = new IPEndPoint(ipAddress,/*MyPort*/);
Socket sender = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp );
try {
sender.Connect(remoteEP);
Console.WriteLine("Socket connected to {0}",sender.RemoteEndPoint.ToString());
bool _continue = true;
while (_continue)
{
if (sender.Available>0)
{
int bytesRec = sender.Receive(bytes);
string a = Encoding.ASCII.GetString(bytes, 0, bytesRec);
Console.WriteLine(a);
if (a == "exit")
{
sender.Shutdown(SocketShutdown.Both);
sender.Close();
_continue = false;
}
}
}
Console.ReadKey();
} catch (ArgumentNullException ane) {
Console.WriteLine("ArgumentNullException : {0}", ane.ToString());
Console.ReadKey();
} catch (SocketException se) {
Console.WriteLine("SocketException : {0}", se.ToString());
Console.ReadKey();
} catch (Exception e) {
Console.WriteLine("Unexpected exception : {0}", e.ToString());
Console.ReadKey();
}
} catch (Exception e) {
Console.WriteLine( e.ToString());
Console.ReadKey();
}
}
}
}
I hope the question was clear and you will answer it,
Itay

Well, I found a solution very fast.
I just port-forwarded the port im using to the server ip.
for example if server ip is 10.0.0.1 and port is 2222
I just needed to forward port 2222 in with "lan users" 10.0.0.1.
Thank you for your help anyway.

Related

C# create multi threaded socket server and select client/connection

Currently, I'm programming in C#, I would like to modify the code below to isolate one client connection. so like creating a break-out room from the main pool.
Below are 2 files, one is just the basic standard .NET Framework Console App Program.cs file; the other is the server file. Combined, they both can make a multi-threaded server, but I would like one that allows me to also select a client to connect to in case if I were to create a remote control application as my friend did.
On a side note, I would like to share that I want to be able to connect to a client by entering connect [1,2,3,etc..] into the console.
Answers
If you answer, please put some code, It would really, really help. I learn a lot better by looking att the code rather than reading documentation.
Code
Server.cs
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace TCPServer
{
class Server
{
TcpListener server = null;
int counter = 0;
public Server(string ip, int port)
{
IPAddress localAddr = IPAddress.Parse(ip);
server = new TcpListener(localAddr, port);
server.Start();
StartListener();
}
public void StartListener()
{
try
{
while (true)
{
Console.WriteLine("Waiting for incoming connections...");
TcpClient client = server.AcceptTcpClient();
counter += 1;
Console.WriteLine("Connected to authorized client: {0}", counter);
Thread t = new Thread(new ParameterizedThreadStart(HandleDeivce));
t.Start(client);
}
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
server.Stop();
}
}
public void HandleDeivce(Object obj)
{
TcpClient client = (TcpClient)obj;
var stream = client.GetStream();
string imei = String.Empty;
string data = null;
Byte[] bytes = new Byte[256];
int i;
try
{
while ((i = stream.Read(bytes, 0, bytes.Length)) != 0)
{
string hex = BitConverter.ToString(bytes);
data = Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("{1}: Received: {0}", data, Thread.CurrentThread.ManagedThreadId);
if (data != "auth token")
{
stream.Close();
client.Close();
}
string str = "Device authorization successfull";
Byte[] reply = System.Text.Encoding.ASCII.GetBytes(str);
stream.Write(reply, 0, reply.Length);
Console.WriteLine("{1}: Sent: {0}", str, Thread.CurrentThread.ManagedThreadId);
}
}
catch (Exception e)
{
Console.WriteLine("Exception: {0}", e.ToString());
client.Close();
}
}
}
}
Program.cs
using System;
using System.Threading;
namespace TCPServer
{
class Program
{
static void Main(string[] args)
{
Thread thread = new Thread(delegate()
{
Server server = new Server("127.0.0.1", 13000);
});
thread.Start();
Console.WriteLine("Server started...");
}
}
}

C# socket client server disconection

Hi i have the following socket server/client codes which another stackoverflow member gave me.
Basically the server listens to multiple clients, it all works good and smooth but when a client exits the app the server crashes because of unexpected disconnect.
I read about heartbeed but don't know how to implement it as im quite a noob at c#
Below are the codes
Server:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class AsynchIOServer
{
static System.Collections.Concurrent.ConcurrentBag<Socket> ConnectedClients = new System.Collections.Concurrent.ConcurrentBag<Socket>();
static void Process(Socket client)
{
Console.WriteLine("Incoming connection from " + client.RemoteEndPoint);
const int maxMessageSize = 1024;
byte[] response;
int received;
while (true)
{
if (client.Poll(-1, SelectMode.SelectRead))
{
// Receive message from the server:
response = new byte[maxMessageSize];
received = client.Receive(response);
if (received == 0)
{
Console.WriteLine("Client closed connection!");
if (!ConnectedClients.TryTake(out client))
Console.WriteLine("Error when removing connection socket object from list (" + client.RemoteEndPoint + ")!");
return;
}
List<byte> respBytesList = new List<byte>(response);
respBytesList.RemoveRange(received, maxMessageSize - received); // truncate zero end
Console.WriteLine("Client " + client.RemoteEndPoint + " : " + Encoding.ASCII.GetString(respBytesList.ToArray()));
}
}
}
public static void Main()
{
int backlog = -1, port = 2222;
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.ReceiveTimeout = -1;
// Start listening.
try
{
server.Bind(new IPEndPoint(IPAddress.Any, port));
server.Listen(backlog);
}
catch (Exception)
{
Console.WriteLine("Listening failed!");
Console.ReadKey();
return;
}
Console.WriteLine("Start listening...");
new System.Threading.Thread(() => {
while (true)
{
Socket client = server.Accept();
ConnectedClients.Add(client);
new System.Threading.Thread(() => {
try { Process(client); }
catch (Exception ex)
{
Console.WriteLine(client.RemoteEndPoint + " client connection processing error: " + ex.Message);
if (!ConnectedClients.TryTake(out client))
Console.WriteLine("Error when removing connection socket object from list (" + client.RemoteEndPoint + ")!");
}
}).Start();
}
}).Start();
while (true)
{
byte[] sent = Encoding.ASCII.GetBytes(Console.ReadLine());
if (sent.Length == 0) break;
foreach (Socket s in ConnectedClients.ToArray()) s.Send(sent);
}
Console.WriteLine("Press any key for exit...");
foreach (Socket s in ConnectedClients.ToArray()) s.Close();
Console.ReadKey();
}
}
Client:
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class Client
{
static void WorkWithServer(Socket server)
{
const int maxMessageSize = 1024;
byte[] response;
int received;
while (true)
{
try
{
// Receive message from the server:
response = new byte[maxMessageSize];
received = server.Receive(response);
if (received == 0)
{
Console.WriteLine("Server closed connection.");
return;
}
List<byte> respBytesList = new List<byte>(response);
respBytesList.RemoveRange(received, maxMessageSize - received); // truncate zero end
Console.WriteLine("Server: " + Encoding.ASCII.GetString(respBytesList.ToArray()));
// Send message to the server:
/* Console.Write("You: ");
server.Send(Encoding.ASCII.GetBytes(Console.ReadLine()));
Console.WriteLine(); */
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
return;
}
}
}
static public void Main(string[] Args)
{
IPEndPoint serverEp = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 2222);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.ReceiveTimeout = -1;
// Connect to the server.
try { server.Connect(serverEp); }
catch (Exception)
{
Console.WriteLine("Establish connection with server (" + serverEp + ") failed!");
Console.ReadKey();
return;
}
Console.WriteLine("Connection with server (" + serverEp + ") established!");
WorkWithServer(server);
Console.WriteLine("Press any key for exit...");
Console.ReadKey();
}
}
Apart from that i want the server to receive data from another server and once received transmit it to all the connected clients
I know i am probabily asking for too much but as i said my c# skills are almost none and i cannot afford paying someone

connecting POP3 via http proxy using HigLabo

I'm using HigLabo to create an email client. Also I need to use an http proxy.
But authentication fails every time.
I found the base code here : .net pop3 over http proxy
Here is my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HigLabo.Net;
using HigLabo.Net.Pop3;
using System.Net.Sockets;
using System.Threading;
namespace ConsoleApplication1
{
class Program
{
static Pop3Client pop;
static Socket socket;
static void Main(string[] args)
{
String proxyAddr = "112.241.212.104"; //This seemed to be working
int proxyPort = 8585;
byte[] buffer = new byte[25];
pop = new Pop3Client("PopClient");
socket = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,
ProtocolType.Tcp);
Console.WriteLine("Connecting to proxy...");
socket.Connect(proxyAddr, proxyPort);
Console.WriteLine("Connected to proxy");
Console.WriteLine("Sending Packets...");
socket.Send(Encoding.UTF8.GetBytes("CONNECT pop.mail.yahoo.com:995 HTTP/1.1<CR><LF>"));
socket.Send(Encoding.UTF8.GetBytes("<CR><LF>"));
Console.WriteLine("Packets sent");
Console.WriteLine("Waiting for response...");
socket.Receive(buffer);
Console.WriteLine("Packets received");
Console.WriteLine("Time Elapsed : " + timeElapsed + " seconds");
Console.WriteLine("Connectong POP to socket...");
if (pop.Connect(socket))
{
pop.Connect();
Console.WriteLine("Connection completed");
}
else
{
Console.WriteLine("Disconnected");
Disconnect();
return;
}
pop.Ssl = true;
pop.UserName = "EMAIL_ADDRESS";
pop.Password = "PASSWORD";
pop.ServerName = "pop.gmail.com";
pop.Port = 995;
Console.WriteLine("Authenticating...");
if (pop.Authenticate())
{
Console.WriteLine("Authentication completed"); //Never comes here
GetMail();
}
else
{
Console.WriteLine("Authentication failed"); //Always comes here
Disconnect();
}
}
private static void GetMail()
{
HigLabo.Mime.MailMessage msg = pop.GetMessage(1);
Console.WriteLine(msg.BodyText);
}
static void Disconnect()
{
Console.WriteLine("Disconnecting...");
pop.Close();
socket.Close();
Console.WriteLine("Disconnected");
}
}
}
I gave permission for the app also.
What is wrong here?
Are there any other/better/easy ways to do this? May be with a different library?
This is wrong: <CR><LF>.
What you want to use is \r\n in your strings.

Socket Programming - A connection attempt failed Exception

Am new to socket programming and am creating a chat application.As like other applications whenever i press enter in a chat window it should send the chat to a particular user.Am maintaining a DB for all users along with their IPAddresses.So whenever i select a user for sending chat it should send to the corresponding IPAddress.As of now am trying to send chat to my own machine(so i hard coded the IPAddress of my machine).But am getting an exception when i try to send my code to my IPAddress.Can anyone please help me out.
My code for socket programming is this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.IO;
using System.Net.Sockets;
namespace Ping
{
class SocketProgramming
{
//Socket m_socWorker;
public AsyncCallback pfnWorkerCallBack;
public Socket m_socListener;
public Socket m_socWorker;
public void sendChat(IPAddress toMessengerIP)
{
try
{
//create a new client socket ...
m_socWorker = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
String szIPSelected = toMessengerIP.ToString();
String szPort = "7777";
int alPort = System.Convert.ToInt16(szPort, 10);
System.Net.IPAddress remoteIPAddress = System.Net.IPAddress.Parse(szIPSelected);
System.Net.IPEndPoint remoteEndPoint = new System.Net.IPEndPoint(remoteIPAddress, alPort);
// receive();
m_socWorker.Connect(remoteEndPoint);
//Send data
Object objData =(object)"hi dhivi";
byte[] byData = System.Text.Encoding.ASCII.GetBytes(objData.ToString());
m_socWorker.Send(byData);
}
catch (System.Net.Sockets.SocketException se)
{
//MessageBox.Show(se.Message);
Console.Out.Write(se.Message);
}
}
public void receive()
{
try
{
//create the listening socket...
m_socListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 7777);
//bind to local IP Address...
m_socListener.Bind(ipLocal);
//start listening...
m_socListener.Listen(4);
// create the call back for any client connections...
m_socListener.BeginAccept(new AsyncCallback(OnClientConnect), null);
//cmdListen.Enabled = false;
}
catch (SocketException se)
{
Console.Out.Write(se.Message);
}
}
public void OnClientConnect(IAsyncResult asyn)
{
try
{
m_socWorker = m_socListener.EndAccept(asyn);
WaitForData(m_socWorker);
}
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0, "1", "\n OnClientConnection: Socket has been closed\n");
}
catch (SocketException se)
{
Console.Out.Write(se.Message);
}
}
public class CSocketPacket
{
public System.Net.Sockets.Socket thisSocket;
public byte[] dataBuffer = new byte[1];
}
public void WaitForData(System.Net.Sockets.Socket soc)
{
try
{
//if (pfnWorkerCallBack == null)
//{
// pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
//}
CSocketPacket theSocPkt = new CSocketPacket();
theSocPkt.thisSocket = soc;
// now start to listen for any data...
soc.BeginReceive(theSocPkt.dataBuffer, 0, theSocPkt.dataBuffer.Length, SocketFlags.None, pfnWorkerCallBack, theSocPkt);
}
catch (SocketException se)
{
Console.Out.Write(se.Message);
}
}
}
}
And whenever the users clicks the enter button it should call the sendChat() method.
private void txt_Userinput_KeyDown_1(object sender, KeyEventArgs e)
{
Window parentWindow = Window.GetWindow(this);
TabItem tb = (TabItem)this.Parent;
string user = tb.Header.ToString();
if (e.Key == Key.Return)
{
richtxtbox_chatwindow.AppendText(Environment.NewLine + user + " : " + txt_Userinput.Text);
DBCoding dbObject = new DBCoding();
SocketProgramming socketObj = new SocketProgramming();
socketObj.sendChat(IPAddress.Parse("192.168.15.41"));
}
else { return; }
}
To get ipaddress of the user
public IPAddress getIP()
{
String direction = "";
WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
using (WebResponse response = request.GetResponse())
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
direction = stream.ReadToEnd();
}
//Search for the ip in the html
int first = direction.IndexOf("Address: ") + 9;
int last = direction.LastIndexOf("</body>");
direction = direction.Substring(first, last - first);
IPAddress ip = IPAddress.Parse(direction);
return ip;
}
You never seem to be calling your receive method. If your application never starts listening, no one will ever be able to connect. If you've tried that, and is getting an exception, post that and we'll go from there.

C# Server and Java Client

I'm trying to write a small client server program. The Server is in C#, and the client is in Java.
Here are the codes:
Server:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace Server
{
class Program
{
private TcpListener tcpListener;
public static void Main(string[] args)
{
Program program = new Program();
program.StartServer();
while (true) ;
}
private bool StartServer()
{
IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
try
{
tcpListener = new TcpListener(ipAddress, 5678);
tcpListener.Start();
tcpListener.BeginAcceptTcpClient(new AsyncCallback(this.ProcessEvents), tcpListener);
Console.WriteLine("Listing at Port {0}.", 5678);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
return false;
}
return true;
}
private void ProcessEvents(IAsyncResult asyn)
{
try
{
TcpListener processListen = (TcpListener)asyn.AsyncState;
TcpClient tcpClient = processListen.EndAcceptTcpClient(asyn);
NetworkStream myStream = tcpClient.GetStream();
if (myStream.CanRead)
{
StreamReader readerStream = new StreamReader(myStream);
string myMessage = readerStream.ReadToEnd();
readerStream.Close();
}
myStream.Close();
tcpClient.Close();
tcpListener.BeginAcceptTcpClient(new AsyncCallback(this.ProcessEvents), tcpListener);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
Client:
import java.io.PrintWriter;
import java.net.Socket;
public class Program {
public static void main(String[] args) {
Socket socket;
try {
socket = new Socket( "127.0.0.1", 5678);
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.print("Hello world");
writer.flush();
writer.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
But when I try to create a Socket in client, I get this exception:
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at java.net.Socket.<init>(Unknown Source)
at Program.main(Program.java:10)
Can anyone tell me what I'm doing wrong here?
updated: I'm running x64 Windows 7 Ultimate, I don't see anything firewall message pop up (I did saw it for server once, which I allowed and set to always allow). I can connect using telenet, no problem with that. Any other suggestion please.
I have finally figured out the problem myself.
The .Net server was by default using ipv6 address, and Java client was using the ipv4 address. To create a ipv4 address use:
TcpListener tcpListener = new TcpListener(IPAddress.Any, 5678);
instead of:
IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
TcpListener tcpListener = new TcpListener(ipAddress, 5678);

Categories