Code archives/Networking/Socket Reading

This code has been declared by its author to be Public Domain code.

Download source code

Socket Reading by Retimer2008
Nothing special. Just an assistant.

Very simple list of functions to prevent stream-read errors. This is mainly meant for security reasons, preventing a client from freezing the server, or crashing it by packet sniffing and altering the format of packets to the server. This was a major issue for me, maybe it will help someone else who is new to blitz net api.

What it basically does is it checks if the socket has anything available to read. If it doesn't, then the socket and stream will be closed

Make sure to use this as well, to prevent writing to a closed socket and save yourself from unneeded cpu cycles:

If SocketConnected(Socket[i]) <> True
>>>unload socket and stream, and prevent it from being continually checked in loop
End If
Function MReadByte:Byte(Socket:TSocket,Stream:TStream)
	If SocketReadAvail(Socket) >= 1
		Return ReadByte(Stream)
	Else
		CloseSocket(Socket)
		CloseStream(Stream)
		Return 0
	End If
End Function

Function MReadShort:Short(Socket:TSocket,Stream:TStream)
	If SocketReadAvail(Socket) >= 2
		Return ReadShort(Stream)
	Else
		CloseSocket(Socket)
		CloseStream(Stream)
		Return 0
	End If
End Function

Function MReadInt:Int(Socket:TSocket,Stream:TStream)
	If SocketReadAvail(Socket) >= 4
		Return ReadInt(Stream)
	Else
		CloseSocket(Socket)
		CloseStream(Stream)
		Return 0
	End If
End Function

Function MReadLong:Long(Socket:TSocket,Stream:TStream)
	If SocketReadAvail(Socket) >= 8
		Return ReadLong(Stream)
	Else
		CloseSocket(Socket)
		CloseStream(Stream)
		Return 0
	End If
End Function

Function MReadFloat:Float(Socket:TSocket,Stream:TStream)
	If SocketReadAvail(Socket) >= 4
		Return ReadFloat(Stream)
	Else
		CloseSocket(Socket)
		CloseStream(Stream)
		Return 0
	End If
End Function

Function MReadDouble:Double(Socket:TSocket,Stream:TStream)
	If SocketReadAvail(Socket) >= 8
		Return ReadDouble(Stream)
	Else
		CloseSocket(Socket)
		CloseStream(Stream)
		Return 0
	End If
End Function

Function MReadString:String(Socket:TSocket,Stream:TStream,length:Int)
	If SocketReadAvail(Socket) >= length
		Return ReadString(Stream,length)
	Else
		CloseSocket(Socket)
		CloseStream(Stream)
		Return ""
	End If
End Function

Function MReadLine:String(Socket:TSocket,Stream:TStream)
	If SocketReadAvail(Socket) >= 0
		Return ReadLine(Stream)
	Else
		CloseSocket(Socket)
		CloseStream(Stream)
		Return ""
	End If
End Function

Comments

None.

Code Archives Forum