Reputation: 143
I am rather new to socket programming but here goes nothing.
I have been trying to do some simple TCP communications between a C# server and a PHP client. However, I have had no luck in getting a connection between them. I am basically sending a desktop application messages through the web browser via PHP socket communication. However, I keep getting a timeout error.
My code is the following:
My C# Server code - It simply listens and notifies me if a connection is made
static void Main(string[] args)
{
try
{
IPAddress localAddress = IPAddress.Parse("xx.xx.xx.xx");
TcpListener listener = new TcpListener(localAddress, 4761);
listener.Start(1);
while (true)
{
Console.WriteLine("Server is waiting on socket {0}", listener.LocalEndpoint);
TcpClient client = listener.AcceptTcpClient();
NetworkStream IO = client.GetStream();
Console.WriteLine("Recieved a connection from {0}", client.Client.RemoteEndPoint);
Console.WriteLine("Time to depart.");
client.Close();
}
}
catch (Exception E)
{
Console.WriteLine("Caught exception: {0}", E.ToString());
}
}
PHP Client - This is a function I made that simply connects to the server (failing miserably)
public function Hook_Up($Host_IP)
{
$this->String_and_Cup = fsockopen("xx.xx.xx.xx", 4761);
if($this->String_and_Cup)
{
echo "Congratulations, it's a socket connection...";
}
else
{
echo "I'm sorry, the socket connection didn't make it...";
}
}
All I want to do so far is connect to this server through the browser. I'd appreciate the input on how to do so.
Thanks in advance.
Upvotes: 0
Views: 1853
Reputation: 4995
I dont think what you are trying to achieve should be done this way. You will not be able to connect to a tcp port over the http which is the protocol the browser uses. The PHP socket you created must be run from the command line in order for it to work correctly.
From what is can tell you, you might wanna have a look at the web sockets which is an html5 implementation which is currently supported by newer versions of chrome and firefox. The web sockets uses a web socket protocol to implement push based systems where you can have a server that uses a memory queue such as an active mq to push the messages from the server and the client which is the browser should subscrbe to these messages from the server over the queue.
TCP sockets are not meant for browsers. If how ever you wanna connect to a tcp socket from server you can do it just using javascript as given here http://ajaxian.com/archives/tcpsocket-sockets-in-the-browser
var conn = new TCPSocket(hostname, port)
conn.onopen = function() { alert('connection opened!') }
conn.onread = function(data) { alert('RECEIVE: ' + data) }
conn.onclose = function(data) { alert('connection closed!') }
conn.send('Hello World');
Upvotes: 2