0
votes

My understanding for now about client-server connections in C#:

  • TCPListener = Server
  • TCPClient = Client

In alternative to this exists a "Socket" class which can be used as Client and as Server, but at the end do both variants the same thing?!

I understand the TCPClient. It has a getStream() method, which returns a NetWorkStream which has methods for read and write from/to the stream.

My problem is the TCPListener on the server-side. The TCPListener has not a getStream() method and also no read/write method. How i can read/write from the TCPListener from/to the stream?

3
while(true) { var tcpClient = tcpListener.AcceptTcpClient(); /*use tcpClient*/ }L.B

3 Answers

2
votes

TCP supports bidirectional streaming. Once a connection is established, there's not much difference between the client and the server ends.

You would use TcpListener.AcceptTcpClient to establish the connection and give the server side its TcpClient instance.

You mention sending messages in your question title. One important thing to bear in mind is that if you're working at this low level with TCP, there's no inherent "messaging" layer - calls of Send at one end are not matched 1-1 with calls of Receive at the other end. If you want messaging you have to build that yourself on top of these primitives, or switch to a higher level networking library (e.g. WCF) which automatically hides this level of detail.


Basically, the TcpListener class acts along the lines of "I intend to allow people to connect to me" - and calls to Accept* like methods are the way of saying "if anyone's currently asking to connect with me, let's create that connection now and start talking"

0
votes

TcpListener lets you accept incoming connections using eg. the AcceptTcpClient method. This returns a TcpClient instance you can use for bi-directional communication with the client.

TCP is a protocol built around connections, so you can't really send or receive data without estabilishing a connection first - that applies to both the client and server.

0
votes

You can use the TcpClient's stream to both receive and send data from/to the client
the TcpListener only listens for requests, it cannot interact with them.