Jump to content

Help me learn more about PHP socket connection TCP! Please help me out!


Recommended Posts

Hello guys,


I'm trying to learn and understand the process of connecting a client to TCP connection!


Now I'm trying to build a mobile chat application which I want it to connect to my server (hosted in media temple) which I hate about media temple is the way they name the variable we used to know like "localhost" to some random strange string!


anyway that's not the topic. But you got the idea it's a chat app as the client on a mobile device! that will try to connect to my server.


Now I have tried sooo many scripts, tutorials ... etc. But I didn't get it. I need to know the process or even get it to work so I'll be able to know what's going on from the code.


Here's what I have (as of now) on the mobile (client side):


// create the socekt object
var socket = Titanium.Network.createTCPSocket({
port:4446,  // some port I just typed because I don't know what port!

// connect button
connectBtn.addEventListener('click', function() {
if(socket.isValid == false){
	try {
	    messageLabel.text = 'Opened!';
	} catch (e) {
	    messageLabel.text = 'Exception: '+e;

// reader listener 
socket.addEventListener('read', function(e) {
Ti.API.info(e['from'] + ':' + e['data'].text);

//writer button
writeButton.addEventListener('click', function() {
try {
} catch (e) {


//##    Credits goes to people in: http://www.functionblog.com/?p=67=1#viewSource

// Configuration variables
$host = "";
$port = 4041;
$max = 20;
$client = array();

// No timeouts, flush content immediatly

// Server functions
function rLog($msg){
             $msg = "[".date('Y-m-d H:i:s')."] ".$msg;

// Create socket
$sock = socket_create(AF_INET,SOCK_STREAM,0) or die("[".date('Y-m-d H:i:s')."] Could not create socket\n");
// Bind to socket
socket_bind($sock,$host,$port) or die("[".date('Y-m-d H:i:s')."] Could not bind to socket\n");
// Start listening
socket_listen($sock) or die("[".date('Y-m-d H:i:s')."] Could not set up socket listener\n");

rLog("Server started at ".$host.":".$port);
// Server loop
             // Setup clients listen socket for reading
             $read[0] = $sock;
             for($i = 0;$i<$max;$i++){
                          if($client[$i]['sock'] != null)
                                       $read[$i+1] = $client[$i]['sock'];
             // Set up a blocking call to socket_select()
             $ready = socket_select($read,$write = NULL, $except = NULL, $tv_sec = NULL);
             // If a new connection is being made add it to the clients array
                          for($i = 0;$i<$max;$i++){
                                                    if(($client[$i]['sock'] = socket_accept($sock))<0){
                                                                 rLog("socket_accept() failed: ".socket_strerror($client[$i]['sock']));
                                                                 rLog("Client #".$i." connected");
                                       }elseif($i == $max - 1){
                                                    rLog("Too many clients");
                          if(--$ready <= 0)
                                       $input = socket_read($client[$i]['sock'],1024);
                                       $n = trim($input);
                                       $com = split(" ",$n);
                                                                 // Disconnect requested
                                                                 rLog("Disconnected(2) client #".$i);
                                                                              socket_write($client[$p]['sock'],"DISC ".$i.chr(0));
                                                                 if($i == $adm){
                                                                              $adm = -1;
                                                    // Server termination requested
                                                    rLog("Terminated server (requested by client #".$i.")");
                                                    // Strip whitespaces and write back to user
                                                    // Respond to commands
                                                    /*$output = ereg_replace("[ \t\n\r]","",$input).chr(0);
                                                                 rLog("Client #".$i." requested a policy file...");
                                                                 $cdmp="<?xml version=\"1.0\" encoding=\"UTF-8\"?><cross-domain-policy xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://www.adobe.com/xml/schemas/PolicyFileSocket.xsd\"><allow-access-from domain=\"*\" to-ports=\"*\" secure=\"false\" /><site-control permitted-cross-domain-policies=\"master-only\" /></cross-domain-policy>";
                                                    // Close the socket
                                                    //rLog("Disconnected(1) client #".$i);
// Close the master sockets


I just want to understand how am I gonna implement this! I need to know how does it work!


You help is much appreciated!

Link to comment
Share on other sites

I'm not sure what you want help with here, since you've cribbed code from other places, and you really haven't provided any clear questions, or pinpointed any problems, or provided debugging info.


With that said, I can make a general observation which is that php is not generally a great language for writing a socket server or even a client.  It's strength is running as a cgi or apache module and serving web pages.  People typically write their socket servers in something leaner -- c/c++, perl or python are more commonly used for this, and of course you can do it with java.  Of course if you are going to do it in php, then you're going to run it using the cli version of php.


Now to the more specific, and since you brought it up... you do realize that if you setup a socket server, and it's bound to localhost ( that is not a public interface, so no processes that are not running on the same server are going to be able to connect to it?


The other thing you would need to do to the code you presented is actually implement the chat protocol.  Your client seems to be sending json and expecting the same, and your socket server application doesn't look like it has any json send or receive logic in it.

Link to comment
Share on other sites

Youll need port 80 for TCP, UDP and HTTP requests. Hostname should be an IP


Huh?  Port 80 is reserved for HTTP, so that socket would be grabbed by a webserver if running.  It also has nothing to do with TCP/UDP.  TCP is a connection oriented protocol whereas UDP is a datagram protocol. 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.