TCP IP SERVER

Just starting out? Need help? Post your questions and find answers here.
BackupUser
PureBasic Guru
PureBasic Guru
Posts: 16777133
Joined: Tue Apr 22, 2003 7:42 pm

Post by BackupUser »

Restored from previous forum. Originally posted by Pantcho.

hello.
i am trying to do a server with threads
threading is a very known method of using it to do servers and stuff.
all i wanted to do is a proggie that will work like this
1. main loop of server waiting for new connection
2. if a connection dedected then a new Thread is open
a thread that will handle that certin user while server is
still waiting for other users to connect
i know u ppl like to work on a loop that will include everthing
but i want to do it with threads since its faster. (proven)
3. here is what i wrote until now
doesnt work dont know why...it runs but the procedure that handle
the user cant dedect his disconnection or ...PLZ CHECK IT ! :P

==================Begin Server.pb==========================
;to check this source i used NetworkClient.PB from examples
;
If InitNetwork() = 0
MessageRequester("Error", "Can't initialize the network !", 0)
End
EndIf


; this is the data analyzing - CLient requests from server and stuff....
Procedure UserConnect(theclientid)

userquit = 0
Repeat
If theclientid = NetworkClientID()

ClientEvent = NetworkServerEvent()
If ClientEvent

Select ClientEvent

Case 5

UserMsg$ = ReceiveNetworkString(theclientid)
MessageRequester("msg from client:" + Str(theclientid),UserMsg$,0)
UserMsg$ = ""

Case 4
ConClients = ConClients - 1
userquit = 1
Goto 20 ; 20 is a sub
EndSelect
EndIf
EndIf

Until userquit = 1
20:
MessageRequester("end","ended!",0)
EndProcedure



; all var ans strings
; strings:
; ****
Global ConClients

; vars:
ServerPort = 1025 ; DO A MULTIPORT
ConClients = 0
If CreateNetworkServer(ServerPort)

OpenWindow(0, 100, 200, 230, 0, #PB_Window_SystemMenu, "TCP SERVER" + " (Port "+Str(ServerPort)+")")

Repeat
WEvent.l = WindowEvent()
SEvent.l = NetworkServerEvent()

If WEvent = #PB_EventCloseWindow
QuitServer = 1
EndIf

If SEvent

ClientID.l = NetworkClientID()

Select SEvent

Case 1 ; When a new client has been connected...
ConClients = ConClients + 1 ; Create Thread
CreateThread(@UserConnect(),ClientID)


EndSelect
Else

; Sleep_(20) ; Don't stole the whole CPU !
EndIf

Until QuitServer = 1

Else ; cant open the server
MessageRequester("Error","Server Cannot Be Opened, Port in Use??",0)
EndIf

End
; END OF THE MAIN LOOP
==========================end of file===========================

plz do help me its important for me it will be in threads
oh and dont use win32api and other stuff cuz i am on the shareware
version. :P