   #Include "win/winsock2.bi"
    Dim wsData as wsaData
    Dim wVer as long
    Dim errorCheck as integer
    Dim Shared as socket ServerSocket,ClientSocket(100)
    Dim NetworkInfo as sockaddr_in

Dim Shared As String namef(1000)
Dim Shared As Integer maxc=1
Dim k As String 

    wVer = makeword(1,1)
    if wsaStartUp ( wVer, @wsData) = SOCKET_ERROR then
       print "Error 1: ", wsaGetLastError()
       wsaCleanUp()
    else
       print "ok"
    end if

    ServerSocket = opensocket( AF_INET, SOCK_STREAM, IPPROTO_TCP )

    if ServerSocket = INVALID_SOCKET then
       print "Error 2: ", wsaGetLastError()
    else
       print "ok"
    end if

    with NetworkInfo
        .sin_family      = AF_INET
        .sin_port        = htons( 9999 )
        .sin_addr.S_addr = INADDR_ANY
    end with

    if bind(ServerSocket, Cast(PSOCKADDR,@NetworkInfo),sizeof(sockaddr)) = SOCKET_ERROR then
       print "Error 3: ", wsaGetLastError()
    else
       print "ok"
    end if

    if listen(ServerSocket,5) = socket_error then
       print "Error 4: ", wsaGetLastError()
    else
       print "ok"
    end If
Print "WAITING.."

'messages
Sub threadx( id As integer )
dim as zstring*316 nn
Dim As Byte bytes

bytes = recv( ClientSocket(id), @nn , 316, 0 )
If nn<>"" Then
print "Client " & namef(id) & ":" &   nn

'change name only in server
If InStr(nn,"name:") Then
	namef(id)=mid(nn,6)
EndIf
'block without name
If namef(id)="" Then
	ClientSocket(id)=0
	closesocket(ClientSocket(id))
EndIf

'client disconnected
If nn="exit" Then
	ClientSocket(id)=0
	closesocket(ClientSocket(id))
	Print namef(id) & " " & "disconnected"
	nn=namef(id) & "------" & "disconnected"
	beep
EndIf

'send to all
For i As Integer=1 To maxc
If i<>id And ClientSocket(i)<>0 Then
	send(ClientSocket(i),@nn,316,0)
EndIf
Next
EndIf

End Sub

Dim As ulong iMode=1 : IOCtlSocket(ServerSocket, FIONBIO, @iMode) 'SET NON-BLOCKING

Do

'CLIENT CONNECTED??-------------------------------
ClientSocket(maxc)=Accept(ServerSocket,NULL,null)
If (ClientSocket(maxc) = INVALID_SOCKET) Then
Else
	Print "New Client " & maxc
	maxc+=1
EndIf
'-------------------------------------------------

'get messages-------------------------------------
For i As Integer=1 To maxc-1
If ClientSocket(I)<>0 Then
threadx( i )
EndIf
Sleep 10
Next
'-------------------------------------------------

Sleep 100
k = InKey
If asc(k)=27 Then Exit Do
Loop

'SHUTDOWN
For i As Integer=1 To maxc-1
closesocket(ClientSocket(i))
Next

CloseSocket(ServerSocket)

WSACleanup

Print wsaGetLastError()
Sleep 1000
