samoi Posted February 11, 2011 Share Posted February 11, 2011 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({ hostName:"mywebsite.com", port:4446, // some port I just typed because I don't know what port! mode:Titanium.Network.READ_WRITE_MODE }); // connect button connectBtn.addEventListener('click', function() { if(socket.isValid == false){ try { socket.connect(); socket.listen(); messageLabel.text = 'Opened!'; } catch (e) { messageLabel.text = 'Exception: '+e; } } }); // reader listener socket.addEventListener('read', function(e) { Ti.API.info(JSON.stringify(e)); Ti.API.info(e['from'] + ':' + e['data'].text); }); //writer button writeButton.addEventListener('click', function() { try { socket.write("writing...this"); } catch (e) { alert(e); } }); //## //## Credits goes to people in: http://www.functionblog.com/?p=67=1#viewSource //## <?php // PHP SOCKET SERVER error_reporting(E_ERROR); // Configuration variables $host = "127.0.0.1"; $port = 4041; $max = 20; $client = array(); // No timeouts, flush content immediatly set_time_limit(0); ob_implicit_flush(); // Server functions function rLog($msg){ $msg = "[".date('Y-m-d H:i:s')."] ".$msg; print($msg."\n"); } // 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 while(true){ socket_set_block($sock); // 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 if(in_array($sock,$read)){ for($i = 0;$i<$max;$i++){ if($client[$i]['sock']==null){ if(($client[$i]['sock'] = socket_accept($sock))<0){ rLog("socket_accept() failed: ".socket_strerror($client[$i]['sock'])); }else{ rLog("Client #".$i." connected"); } break; }elseif($i == $max - 1){ rLog("Too many clients"); } } if(--$ready <= 0) continue; } for($i=0;$i<$max;$i++){ if(in_array($client[$i]['sock'],$read)){ $input = socket_read($client[$i]['sock'],1024); if($input==null){ unset($client[$i]); } $n = trim($input); $com = split(" ",$n); if($n=="EXIT"){ if($client[$i]['sock']!=null){ // Disconnect requested socket_close($client[$i]['sock']); unset($client[$i]['sock']); rLog("Disconnected(2) client #".$i); for($p=0;$p<count($client);$p++){ socket_write($client[$p]['sock'],"DISC ".$i.chr(0)); } if($i == $adm){ $adm = -1; } } }elseif($n=="TERM"){ // Server termination requested socket_close($sock); rLog("Terminated server (requested by client #".$i.")"); exit(); }elseif($input){ // Strip whitespaces and write back to user // Respond to commands /*$output = ereg_replace("[ \t\n\r]","",$input).chr(0); socket_write($client[$i]['sock'],$output);*/ if($n=="PING"){ socket_write($client[$i]['sock'],"PONG".chr(0)); } if($n=="<policy-file-request/>"){ 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>"; socket_write($client[$i]['sock'],$cdmp.chr(0)); socket_close($client[$i]['sock']); unset($client[$i]); $cdmp=""; } } }else{ //if($client[$i]['sock']!=null){ // Close the socket //socket_close($client[$i]['sock']); //unset($client[$i]); //rLog("Disconnected(1) client #".$i); //} } } } // Close the master sockets socket_close($sock); ?> I just want to understand how am I gonna implement this! I need to know how does it work! You help is much appreciated! Quote Link to comment https://forums.phpfreaks.com/topic/227339-help-me-learn-more-about-php-socket-connection-tcp-please-help-me-out/ Share on other sites More sharing options...
gizmola Posted February 11, 2011 Share Posted February 11, 2011 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 (127.0.0.1) 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. Quote Link to comment https://forums.phpfreaks.com/topic/227339-help-me-learn-more-about-php-socket-connection-tcp-please-help-me-out/#findComment-1172644 Share on other sites More sharing options...
dreamwest Posted February 11, 2011 Share Posted February 11, 2011 Youll need port 80 for TCP, UDP and HTTP requests. Hostname should be an IP Quote Link to comment https://forums.phpfreaks.com/topic/227339-help-me-learn-more-about-php-socket-connection-tcp-please-help-me-out/#findComment-1172655 Share on other sites More sharing options...
gizmola Posted February 11, 2011 Share Posted February 11, 2011 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. Quote Link to comment https://forums.phpfreaks.com/topic/227339-help-me-learn-more-about-php-socket-connection-tcp-please-help-me-out/#findComment-1172660 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.