LinuxQuestions.org
Share your knowledge at the LQ Wiki.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices

Reply
 
Search this Thread
Old 06-08-2005, 07:51 AM   #1
mrobertson
Member
 
Registered: May 2005
Posts: 275

Rep: Reputation: 30
Receiving multiple messages with a php Server


I have the following server wrote in php:

<?php
function giveMeAnArray($delimiter, $string)
{
return explode($delimiter, $string);
}

$read_write = "read";

if($read_write == "read")
{
//Initialize the socket
set_time_limit(50000);
$address = "127.0.0.1";
$port = 10119;
$sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($sock, $address, $port) or die ('Could not bind to address');

//Start listening on the socket
//There could be a 'while true' or something here to make it infinite
//While(true)
// {
socket_listen($sock);

//Accept an incoming connection
$client = socket_accept($sock);
While (true) {
//Read whatever was just sent, 1024 bytes' worth. Make this however long you need.
$global_string = socket_read($client, 1024);

print ("Serving Client!\n");

//Strip whitespace
$global_string = ereg_replace("[ \t\n\r]", "", $global_string).chr(0);

$delim = ',';

$array = giveMeAnArray($delim, $global_string);

//for($i=0; $i < count($array); $i++)
//{
print("Coil ID number: $array[0]\n");
print("Coil Width: $array[1]\n");
print("Footage Count: $array[2]\n");
print("Coil Length: $array[3]\n");
//}

}//Close the while loop here, if you had one

//Close the connection; and the socket itself.
//socket_close($client);
//socket_close($sock);

//print ("Closed socket successfully\n");
//print ("Server exiting now...\n");

} //ends if ("read")
?>

I was under the impression the the commented out while loop would allow me to recive multiple messages from my server but instead it sends my program into a not responding state. My client is setup to send a message every second in the form of a string. I need to be able to accept and print out these strings every second replacing the previously sent strings. Any suggestions on what I am doing wrong here and what I can do to fix it?
 
Old 06-08-2005, 10:56 AM   #2
rstewart
Member
 
Registered: Feb 2005
Location: Sunnyvale, CA
Distribution: Ubuntu
Posts: 205

Rep: Reputation: 38
Hi,

What does the client do with the socket connection after it sends the first string? Does it close out the socket and reopen a new one the next time it needs to send something? If so, then your server needs to be able to handle disconnects and reconnects.

Hope this helps!
 
Old 06-08-2005, 11:46 AM   #3
mrobertson
Member
 
Registered: May 2005
Posts: 275

Original Poster
Rep: Reputation: 30
Here is the code for my client:

Option Explicit

Private Sub Form_Load()

'set the server to connect to
'Winsock1(0).RemoteHost = Winsock1(0).LocalIP
' 127.0.0.1 is always your computer
Winsock1(0).RemoteHost = "127.0.0.1"

'set the remote port
Winsock1(0).RemotePort = "10119"

'initiate the connection request
Winsock1(0).Connect
End Sub


Private Sub Winsock1_Connect(Index As Integer)

'show the connection in the label
Label3.Caption = "Connected to server!"
End Sub


Private Sub Winsock1_Close(Index As Integer)

'When the other end has closed the connection,
' close my end too
Winsock1(Index).Close

'show the connection in the label
Label3.Caption = "Dis-Connected from server!"

End Sub

Private Sub cmdSend_Click(Index As Integer)
Dim strTemp As String
Dim strTemp2 As String
Dim strTemp3 As String
Dim strTemp4 As String

'check to make ure the connection is there
If Winsock1(0).State <> sckConnected Then

'notify user they are not connected
Label3.Caption = "Not Connected!"

'exit the sub before attempting to send
Exit Sub
End If

'get the data from the text boxes on the exitbox form
strTemp = currentcoil_txt.Text + " , "
strTemp2 = currentinwidth_txt.Text + " , "
strTemp3 = processspeed_txt.Text + " , "
strTemp4 = trlength_txt.Text + " , "

'send the data to the other end
Winsock1(0).SendData strTemp
Winsock1(0).SendData strTemp2
Winsock1(0).SendData strTemp3
Winsock1(0).SendData strTemp4

'allow winsock to complete the send
DoEvents

'sets the focus on the textboxes of interest
currentcoil_txt.SetFocus
currentinwidth_txt.SetFocus
processspeed_txt.SetFocus
trlength_txt.SetFocus
End Sub

I connect when the form loads and then close the socket before the message is sent. I have the rest of the code on a timer which is the code that generates my values and I call my Send function. If I need to handle connects and disconnects.....how would I handle that .......if not what seems to look like the problem and how can I fix it?....Thanks a bunch for your willingness to help
 
Old 06-08-2005, 12:55 PM   #4
rstewart
Member
 
Registered: Feb 2005
Location: Sunnyvale, CA
Distribution: Ubuntu
Posts: 205

Rep: Reputation: 38
Hi,

I see your client closing the socket if the server has already closed it, but I don't see where you close the socket before the message is sent. (BTW: doing that would probably result in nothing being sent )

To handle disconnects/reconnects in your server simple encapsulate your listen call, socket accept, data I/O, result printing, close accepted socket in a while(true) loop.

You also may need to play around with using multiple .php scripts or with reinvoking your server using the php "header" command in order to get the new text message updates to occur correctly.
 
Old 06-08-2005, 01:06 PM   #5
mrobertson
Member
 
Registered: May 2005
Posts: 275

Original Poster
Rep: Reputation: 30
If you look at my server code, I do have listen call, socket accept, data I/O, result printing, close accepted socket in a while(true) loop. When I tried to run the server....it went to a not responding state. What would cause this....also how could I fix whatever is wrong?
 
Old 06-08-2005, 01:35 PM   #6
rstewart
Member
 
Registered: Feb 2005
Location: Sunnyvale, CA
Distribution: Ubuntu
Posts: 205

Rep: Reputation: 38
I know that you had these statements. What I think could be happening when you use the while (true) loop is that the web server you are using does not get control back from your web page and presumes that it is busy waiting for something from a client. Consequently, any screen updates that you may do will be ignored by the web server as it hasen't had a chance to see that the current task has completed and a screen update is needed.

How you can fix this is to rearange your code a bit....

First off, presume that you are going to manually need to reload your web page in order to get screen updates to work correctly. This means that you will be using the web server to run your outer loop for you. It also means that all of your code will be executed starting at the first statement of your code each time the page is reloaded. You will need to do something like this: (in pseudo-code, you will need to implement the algorithm yourself in php, sorry but I don't have the time to do that for you right now, plus it is good experience and fun to do yourself.)

if ( listen socket is not opened )
open listen socket
Listen on listen socket
if ( client connects with server)
accept connection
while ( true )
read data
if ( read error )
process error
break
end if
process data
write data to screen
end while
close socket from accept call
reload web page to start over again

This algorithm requires that you preserve the listen socket between page reloads. php allows the saveing and retreiving of global variables that you can use for this. If you don't want to go with global variable, then you can simply close all sockets before doing the reload and don't bother with the initial "if ( listen socket..." statement and always open everything. The drawback to always opening the socket is the overhead involved, using a global will mean that subsequent web page loads will start up faster than the first time.
 
Old 06-09-2005, 07:10 AM   #7
mrobertson
Member
 
Registered: May 2005
Posts: 275

Original Poster
Rep: Reputation: 30
Thanks for your help. I just have one last question.....How exactly and what do you mean by reloading the web page....at the end of the pseudocode. How would you implement "starting over". Also you dont think it could be something wrong with my client code. I was thinking that it could be because I connect on a form load. After the one string is passed it will then go into the not responding state. Could this be a problem or do you think it lies in the server code?
 
Old 06-09-2005, 10:50 AM   #8
rstewart
Member
 
Registered: Feb 2005
Location: Sunnyvale, CA
Distribution: Ubuntu
Posts: 205

Rep: Reputation: 38
Hi,

Sorry for the delay in getting back you. php has the ability of sending raw http headers. Using the php command "header" you can do some pretty interesting things. One of them is to cause the web server to "branch", or load and execute another .php file - even if the file is the same one that is currently being executed. By doing this you are effectively resursively calling yourself, thus setting up your outer infinite loop.

To do this add this php statement at the end of your algorithm:

Code:
header( "Location: http://".$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'] );
Does this make sense to you?
 
Old 06-09-2005, 12:54 PM   #9
mrobertson
Member
 
Registered: May 2005
Posts: 275

Original Poster
Rep: Reputation: 30
Sorry to keep bothering you.....I really do not understand about the header and web server. I have never coded php before and dont really know much about it. Could you go into a little more detail in explaining to me what is going on? To fill you in on my progress. I no longer have a not responding program. I have a server coded that will take an infinite amount of messages. The problem that I am having now is the format of the output . Currently my output is printed as follows:

(first message)
Coil Id is123456
Coil width is 376
Coil length is 786
Footage count is 989

(second message)
Coil Id is654321
Coil width is 8970
Coil length is 675
Footage count is 5432

As you can see it keeps printing the sentences over and over. I need the sentences to be printed only once with the values as the only changing text. I dont want any new lines of text. 4 lines with changing numbers. The values will change as each message somes in. is this possible and if so how would I implement it. Here is my code:

<?php
function giveMeAnArray($delimiter, $string) {
return explode($delimiter, $string);
}

$read_write = "read";

if ($read_write == "read") {
//Initialize the socket
set_time_limit(0);
$address = '127.0.0.1';
$port = 10119;
$counter = 0;
if (($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) < 0) {
echo "socket_create() failed. Reason: " . socket_strerror($sock) . "<BR>";
}
if (($ret = socket_bind($sock, $address, $port)) < 0) {
echo "socket_bind() failed. Reason: " . socket_strerror($ret) . "<BR>";
}

//Start listening on the socket
if (($ret = socket_listen($sock, 5)) < 0) {
echo "socket_listen() failed. Reason: " . socket_strerror($ret) . "<BR>";
}

do {
//Accept an incoming connection
if(($client = socket_accept($sock)) < 0) {
echo "socket_accept() failed. Reason: " . socket_strerror($ret) . "<BR>";
break;
}

do {
//Read whatever was just sent, 1024 bytes' worth. Make this however long you need.
if( false == ($global_string = socket_read($client, 2048))) {
echo "socket_read() failed. Reason: " . socket_strerror($ret) . "<BR>";
break 2;
};

if (!$global_string = trim($global_string)) {
continue;
}
else {
print ("Serving Client!\n");
}

//Strip whitespace
$global_string = ereg_replace("[ \t\n\r]", "", $global_string).chr(0);

$delim = ',';

$array = giveMeAnArray($delim, $global_string);

//print("Coil ID number: $array[0]\n");
//print("Coil Width: $array[1]\n");
//print("Footage Count: $array[2]\n");
//print("Coil Length: $array[3]\n");
for($i=0; $i < count($array); $i++) {
sleep(1);
echo "\r";
echo "update: $i%";
}

$id = $array[0];
$Width = $array[1];
$footagecount = $array[2];
$Length = $array[3];



$counter++;
} while (true);

//Close the connection; Don't leave things like this open...!!
socket_close($client);
} while (true);

//Close the socket itself
socket_close($sock);
print("Coil ID number: $id\n");
print("Coil Width: $Width\n");
print("Footage Count: $footagecount\n");
print("Coil Length: $Length\n");

} //ends if ("read")
 
Old 06-09-2005, 01:12 PM   #10
rstewart
Member
 
Registered: Feb 2005
Location: Sunnyvale, CA
Distribution: Ubuntu
Posts: 205

Rep: Reputation: 38
Try the following: (I think it will give you the behavior you are looking for)

1) Comment out the do { before you Accept an incoming connection

2) Comment out this code
Code:
for($i=0; $i < count($array); $i++) {
sleep(1);
echo "\r";
echo "update: $i%";
}
3) Comment out the last } while (true);

4) Add the line "header( "Location: http://".$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF'] );" at the end of your source after the last printf and before the last }.

Tell me what happens...
 
Old 06-09-2005, 01:23 PM   #11
mrobertson
Member
 
Registered: May 2005
Posts: 275

Original Poster
Rep: Reputation: 30
It really didnt do anything. I got an error on line 37 where I have:

break 2; Fatal error: Cannot break/continue 2 levels in U:\phpProgram2 on line 37

I wanted to let you know that I am currently coding a debugging this from a php debugger/interpreter called tulip. I do not have it on a linux box yet. Will this make a difference in trying to implement that header line. Also was I supposed to put something in place of server_name and php_self?
 
Old 06-09-2005, 01:32 PM   #12
rstewart
Member
 
Registered: Feb 2005
Location: Sunnyvale, CA
Distribution: Ubuntu
Posts: 205

Rep: Reputation: 38
Change "break 2" to "break". We have elliminated the outer do loop so you only have one loop...

I don't know what tulip is so I can't answer for that. If it supports all of the php defined functions then it should work.

You should not need to change the header statement. The variables should be predefined (at least they are in the real php environment)...

Last edited by rstewart; 06-09-2005 at 01:34 PM.
 
Old 06-09-2005, 01:37 PM   #13
mrobertson
Member
 
Registered: May 2005
Posts: 275

Original Poster
Rep: Reputation: 30
Here is the output I got....

Warning: Cannot modify header information - headers already sent by (output started at U:\phpProgram2:44) in U:\phpProgram2 on line 85

Coil Length: 1531
Footage Count: 100
Coil Width: 43.500
Coil ID number: 1323416
socket_read() failed. Reason: Incorrect function.
Serving Client!
Serving Client!
Serving Client!
Serving Client!
Serving Client!
Serving Client!
Serving Client!
Serving Client!
Serving Client!

It ran and I just let it pass 9 messages to see what would happen. This was the output.
 
Old 06-09-2005, 01:55 PM   #14
rstewart
Member
 
Registered: Feb 2005
Location: Sunnyvale, CA
Distribution: Ubuntu
Posts: 205

Rep: Reputation: 38
That output does not make sense to me. You have the data printed out before you start seeing "Serving Client!" messages. I do not see how that can happen. Did you uncomment the output print statements inside your read loop?

I would have expected to see something like the following:

Serving Client!
socket_read() failed: Reason....
Coil Length:...
Footage Count:...
Coil Width:...
Coil ID Number:...

Then if the header command works correctly it should repeat itself with the next batch of data...
 
Old 06-09-2005, 01:59 PM   #15
mrobertson
Member
 
Registered: May 2005
Posts: 275

Original Poster
Rep: Reputation: 30
Like I said before......I am not using a linux operating system...I am using a php editor/interpretor(called "Tulip) that is installed on a windows machine. It prints from the bottom up. I am new to using this software but this is how it has output things all along. What do you think I should do now?
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
php server recieving multiple messages mrobertson Programming 6 06-09-2005 12:55 PM
recieving multiple messages with a php server mrobertson Programming 2 06-06-2005 01:01 PM
Receiving Emails through web server? (PHP) gothgeek84 Programming 12 01-16-2005 03:02 PM
Receiving winpopup broadcast messages vrsic Linux - Software 8 10-30-2003 02:31 AM
Slow when receiving pop3 messages Marty McFly Linux - Newbie 1 10-24-2003 01:07 PM


All times are GMT -5. The time now is 07:18 PM.

Main Menu
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
identi.ca: @linuxquestions
Facebook: linuxquestions Google+: linuxquestions
Open Source Consulting | Domain Registration