How to send packets continuously through TCP? - java

I have one server and multiple clients. The server is sending byte arrays(which includes some kind of messages inside) to the client and client parses those arrays into understandable forms.
Another point is, there is one special kind of message that the server send which client has to respond to it.
I want the server send regular messages continuously without expecting a response, and also special kind of message which expects a response and if it doesn't get it, it will terminate the connection.
How could I do that? I have been checking the net but could not find anything.
Server--->Client(Door Opened)
Server--->Client(Door Closed)
Server--->Client(Are You There?)
Client--->Server(Yeap)
Server--->Client(Plane Has Landed.)
Server--->Client(Are you There?)
.
.
.

Your question is pretty broad, so the answer is broad, too.
Remember about segregation of concerns respectively single responsibility principle. Coming from there: you are actually looking at two different functionalities here:
the regular data transfer from the server to known, connected clients (where no response is expected)
some form of "hearbeat detection" - where the server asks the client to check if they are still reachable/alive
When you think about that, it becomes clear that you probably want to use completely different "components" within client and server to provide these two different functionalities. Like in: even having two different ports (and even different threads) within client/server.
So the server keeps a list of known clients. One thread is sending data to the clients; another thread is periodically iterating that list and asking for heart beat answers. If no answer is coming in time, that client gets removed from the list.

Related

Designing TCP Server/Client Node and Router in Java

I'm a relatively novice programmer and newish to java, and I've been tasked with creating a distributed system that runs two types of applications; a single 'Server/Router' and as many Client-Server 'Nodes' as desired.
-The Server/Router will maintain a table of client connection info
-The Nodes will each send connection info when they spawn
-The Node A can request File F from Node B
---This Request is sent to the router, which looks up connection info for B and sends a request for F
---B begins streaming F to the router, which in turn streams F to A
That's the general idea. It sounds like it would be fairly simple if it weren't for the fact that I've never done ANY distributed computing before... So my question isn't one of how to correct code, but whether my design will work (and if it will not, how I might correct it)
So my idea is to create a public class AVRouter, another class AVNodeInfo, and a third class ConnectionMap; AVRouter will have a collection of AVRouterInfo objects which contain a name, port number, and IP address for each node. It will also have a Queue of ConnectionMap objects, which I'll get to shortly.
AVRouter will have a ServerSocket dedicated to receiving connection info from Nodes when they start up and populating its AVNodeInfo table with said data. It will have another port for file requests; it will use the connection info for the requester and the responder to generate a ConnectionMap object, which it will add the the queue.
The idea being that while there are ConnectionMaps in the queue, it will use the first one to facilitate a transfer.
The last class, AVNode, is much simpler; on spawning it sends its info to the Router, and then it waits for user input to name another node and a file it wishes to request from that node. It will send a completed request to the Router when one is available.
Logic for handling the AVNodeInfo table will probably just be handled with timeouts-if it's been X time since a node has made a request, the node will terminate on its own and the table will delete it from the table on its own... this is a small-scale proof-of-concept type project so it's not really within to scope to handle this nitty-gritty just yet.
So I actually have two questions:
1) Will this design be fine, or should it be improved?
2) How exactly does one handle streaming data from source A through router B to destination C without actually complete transferring from A to B, then from B to C?
I hope this question is within StackOverflow's scope; I know it's design rather than code, but I believe it's specific enough.
The principal concept sounds very ok and is probably the most easy to implement (with the least pitfalls). Its practically a standard approach.
You might want to consider, instead of sending a file from node to server and then forward to the requesting node, to have the nodes connect directly with each other. Node A would just ask the server where is file F and then connect directly to node B.
(that should reduce network load, since data travels a shorter route). But it adds quite some complexity (each node must be able to reach any other node and that makes each node a server). A composite approach would be to try direct connection and if that fails fall back to the via-server method.
You can just implement your original concept and when you have it working, see if you want/need that extension.
Edit: I would probably fuse NodeInfo and Connection (connection as a member of NodeInfo) - the server should have exactly one connection to each node (or if using multiple connections, have NodeInfo hold a collection of the open connections to that specific node).
EDIT: To add to the workability of your concept. Its generally what P2P sharing programs like BitTorrent implement. The "Tracker" acts as the initial "Router" telling each client about other peers. Peers then use direct connections to talk to each other. So its practical identical to what you've come up with, only there is not data traffic using the Server/Router as a bridge (for obvious bandwidth concerns, and it would contradict the P2P idea).

Sending data via tcp sockets. Does this look right?

I'm implementing a client server mechanism where some data is collected from client and sent to the server listening for client calls. I'm doing this using a tcp socket, the data looks like:
Files:20;Users:100;Availability:0.65
Is this in compliance with standards of sending data over tcp sockets ? These are aggregates and I'll be sending it every 5 seconds. How can I improve it ?
There is no standard for sending data over TCP sockets, at least not from user space. The only thing you have to be aware of is that TCP is stream based, so you have no guarantee that message borders will be respected. For example, one recv()-call can result in the application receiving multiple packets.
In order to improve your data format, you could for example remove the descriptions. If you know that each message will contain the same "fields" and in the same order, then they may be redundant.
No it doesn't look right. Whether you realize it or not, you've already made some decisions that may bite you later on, such as reserving ':' and ';', and indeed '\n', so they can't appear in data unless you provide an escape mechanism: have you considered that?
There are plenty of existing protocols to copy or indeed just reuse.

Java Chat system protocol design, how to determine message type?

I have a chat program implemented in Java. The client can send lots of different types of information to the server (i.e, Joins the server and sends username, password; requests a private chat with another user on the server, disconnects from the server, etc).
I'm looking for the correct way to have the server/client differentiate between 'text' messages that are just meant to be chat text messages sent from one client to the others, and 'command' messages (disconnect, request private chat, request file transfer, etc) that are meant for the server or the client.
I see two options:
Use serialized objects, and determine what they are on the receiving end by doing an 'instanceof'
Send the data as a byte array, reserving the first N bytes of the array to specify the 'type' of the incoming data.
What is the 'correct' way to do this? How to real protocols (oscar, irc) handle this situation?
I've googled around on this topic and only found examples/discussions centering on simple java chat applications. None that go into detail about protocol design (which I ultimately intend to practice).
Thanks to any help...
Second approach is much better, because serialization is a complex mechanism, that can be easily used in a wrong way (for example you may bind yourself to internal content of a concrete serialized class). Plus your protocol will be bound to JVM mechanism.
Using some "protocol header" for message differentiation is a common way in network protocols (FTP, HTTP, etc). It is even better when it is in a text form (people will be able to read it).
You typically have a little message header identifying the type of content in all messages, including standard text/chat messages.
Either of your two suggestions are fine. (In your second approach, you probably want to reserve some bytes for the length of the array as well.)

Java networking, beyond a simple chatroom

So I recently followed this tutorial on making a basic chatroom in Java. It uses multithreading and is a "connection-oriented" server. I was wondering how I could use the same Sockets and ServerSockets to send, say, the 3d position of an object instead of just a string?
Currently, the basic chatroom system just sends a string to the server and then the server sends it to all connected clients. What I want is to be able to have a client change the position of an object (most likely their character), and send the change of position to the server. Then (I would imagine) the server would send that change in position to each of the clients connected to it, and each client would in turn render this object at its new position.
I was wondering what the best way to do something like this was?
Would it be to send a string and have the server parse it into a coordinate?
Can I write more than one thing to a DataOutputStream at once?
I feel like I may have explained this poorly, so please ask some clarifying questions.
Thanks!
Create a Domain Object Model for your coordinate system. Then represent the changes to the positions using the objects in the above model. Serialize them into a transportable string like XML, JSON etc. Then unmarshall/deserialize the String to the original object and act upon them.
This separates your transport layer (using sockets to bradcast stuff) from the actual business logic (placement of objects) and the system becomes extendible.

How can I send various information on one socket?

I want to write an application for my android phone to control it via wlan. That should contain its camera abilities.
Is there any elegant method to send live pictures and other information in one socket "at the same time"? My idea is to let the server accept more than one client: the first for life images, the second for information, third for audio streaming...
It should work like skype: you can call people and chat at the same time with one connection. How can I implement something like that?
I doubt multiple sockets would do you any good (unless Android makes it really hard to put data from multiple sources into the same stream). Just send everything sequentially in the same stream, with a tag in front to identify each type of data. The fancy name for this is "time-division multiplexing".
Multiple sockets might make sense if you get into fancy tweaking to, say, give more priority to realtime streams, but I have a feeling that shouldn't be necessary.

Categories

Resources