I want to create chat server and I need to be able to do some things like clear the screen of a specified client, I thought about it and I figured that it would be a good idea if I would send a keyword to the client:
clientSide eg:
if((sporocilo = bufferedReader.readLine()) != null){
if(sporocilo.equals("clearTheScreen"{
object.clearMyScreen
}
}
However there are a lot of commands and the source code would be huge, plus once a client figures out the keyword he could exploit it, how could I do that in another, better way?
Take any example like FTP. Port 20 is used for default data and port 21 is used for Control(authentication etc).And different port mean different socket. After all socket is IP + Port no.
Same is in your case. Use different ports for actual chat data and your service instructions(like clear screen though i don't see why server must clear clients screen). Also instead of string commands like "clearTheScreen" use service ID's and keep a mapping of service ID to functions to be executed. Because if you keep simple string with names like "clear" or "password" with it then it will be easy for other to manipulate data(if it is not encrypyted ofcourse which is another good way to send data).
Related
There are quite a couple of related questions (e.g. Java Socket specify a certain network interface for outgoing connections ) however I couldn't find a satisfying i.e. practical solution to my problem:
On my target (Linux) platform there are multiple network interfaces (eth0...ethN) from which a Server S is reachable. The default route is normally via eth0, however I'm trying to connect S via e.g. eth4 using
new java.net.Socket(IP_of_S, targetport, IP_of_eth4, srcport)
or
sock.bind( eth4_SocketAddress );
sock.connect( S_SocketAddress );
In this example case the IP of eth4 is assigned correctly but traffic is still going out trough the interface of the default route. I've learned this is due to the the "weak end system model" RFC 1122. However I'm wondering whether there's still a Java-based solution to achieving my original goal or whether I have to trigger external iptables or route calls from my program.
(BTW: The outgoing interface needs to be chosen dynamically at runtime, i.e. my program closes the connection and tries to reconnect using a different outbound interface quite frequently.)
As far as I know, you cannot choose the outgoing interface without some routing table setup.
In my opinion, the best solution is to set up a bunch of source-specific routes, routes that match on the source address of a packet, and bind to a given source address in order to select the route (as you already do). There are two ways of achieving that:
use ip rule and multiple routing tables — this is described in http://lartc.org/howto/lartc.rpdb.html ;
use ip route add ... from .... As far as I know, this only works for IPv6, but avoids the complexity of multiple routing tables.
You'll find some background about source-specific routing in https://arxiv.org/pdf/1403.0445v4.pdf (disclaimer, I'm a co-author).
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.)
I've been messing a lot with TCP/IP Communication the last few days (Using Java and C#). I understand how it works and am able to use it. My Question is more a code design question, how its done the best and easy way to make a real communication.
For Example ive Built my own Multiuser Chat Server. I want my Communication to be able to decide wather its an Auth request, or a new chat message the ability to get the current user list etc etc.
Ive implemented a few ways on my own, but im not quite happy About that since i think theres a more standard and beauty way to do this.
My first thought was a String with Delimiters wich gets splitted, here is the Example of my Implementation of my Communication in Java:
//The Object-types im Using
clientSocket = new Socket(host, port_number);
_toServer = new PrintStream(clientSocket.getOutputStream());
_fromServer = new DataInputStream(clientSocket.getInputStream());
//Example Commands my Client sends to the server
_toServer.println("STATUS|"); //Gets the Status if server is online or closed (closed can occur when server runs but chat is disabled)
_toServer.println("AUTH|user|pw"); //Sends an auth Request to Server with username and Password
_toServer.println("MESSAGE|Hello World|ALL"); //Sends hello World in the Normal Chat to all Users
_toServer.println("MESSAGE|Hello World|PRIVATE|foo"); //Sends hello World only to the user "foo"
_toServer.println("USERS|GET"); //Request a list of all Connected Users
//Example In the Recieved Message Method where all The Server Messages Get Analyzed
serverMessage = _fromServer.readLine(); //Reads the Server Messages
String action = serverMessage.split("|")[0];
if (action.equals("USERS")) { //Example "USERS|2|foo;bar"
String users[] = serverMessage.split("|")[2].split(";");
}
if (action.equals("MESSAGE")) { //Example "MESSAGE|Hello World|PRIVATE|foo"
if(serverMessage.split("|")[2].equals("ALL") {
//Code and else for private....
}
}
if (serverMessage.equals("STATUS|ONLINE")) {
// Code
// I leave out //Code and } for the next If statements
}
if (serverMessage.equals("STATUS|OFFLINE")) {
if (serverMessage.equals("AUTH|ACCEPTED")) {
if (serverMessage.equals("AUTH|REJECT")) {
Is this the way its normally Done? Ad You See I need to send Statuscodes and Objects Corresponding to the Code. Ive Thought about Writing the Data in Bytes aswell and Implementing a "Decoder for Each Object", Example:
int action = _fromServer.readInt();
//opcodes is just an Enum Holding the corresponding int
switch(action) {
case(opcodes.MESSAGE):
break;
case(opcodes.AUTH):
break;
}
Note that this is more over a general design Question not just for this Chat Server Example, I think im Implementing a little Network Based Console Game just for Practise.
Is there a better way to do this or even an API/Framework?
Thanks in advance!
Essentially you're designing a protocol. There are a number of communication protocols that can handle this, the main one that comes to mind is IRC. I'm sure you can do a web search for tips on how to implement the protocol.
As for extending something like this for a console game, well I would start with implementing IRC, and using that to learn how real communication protocols are written. Once you've done that you can build on it to add your own commands to your framework.
If you are designing a protocol for inter-language communication, I would suggest not to use formated Strings as a means of communication but statusbytes. If you consider for example the design of TCP/IP itself you will find, messages consist of a fixed-format header and a variable payload. That way you always know, that (e.g.) the third byte of the message contains the messagetype, the fifth denotes an errorstate and so on. This makes handling easier.
If you have designed your protocol, you could consider working with explicit MessageObjects on the java-side, in which case you would implement a factory with marshalling and unmarshalling methods for these objects, converting objects from and to messages in your protocol.
If you are all-java you can even spare that effort and use ObjectInputStreams and ObjectOutputStreams on client and Server. If you are not, you might want to take a look at the Google Protocol Buffers: http://code.google.com/intl/de-DE/apis/protocolbuffers/, which do essentially the same for inter-language communication.
If your project grows, you may want to have a look at Netty - it's a framework for dealing with communication code. If your code is simple, you will be better off doing things manually.
As for protocol design, it depends on what is most important for you: performance, extensibility, human-readability, ease of debugging etc. These criteria may oppose each other to some degree, for example high performance may mean preference for binary protocols, but these negatively impact ease of debugging and sometimes extensibility. It's usually a good idea to not reinvent the wheel. Get inspired by existing protocols. If you choose to go binary, don't start from scratch unless you really have to, start with Protocol Buffers. If your app is simple and not aimed at very high performance, use a human-readable protocol which will make your life easier (debugging and testing are possible with standard shell tools such as strace and nc).
I think Apache MINA will help you. http://mina.apache.org/
Building a Java C/S application is really complex, you need to deal TCP, UDP and multi threads programming; MINA can help you for these things.
I think the other part you need is your private chatting protocol, but how about the open sourced IM service like Jabber? :)
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.
I am writing a java webstart application to deploy from website so users can click and run my software. I need to have a kind of unique machine identification to avoid abusing the accessing of the files. I would like to use the client's MAC address as a unique key so that the server can ensure that no client downloads too much.
Of course, a user may have multiple network cards, so how can my Java application determine the MAC address of the network card that the user is using to access my web site?
..machine identification..
Why not instead do a kind of 'session identification'? As each app. loads (you might want to implement the SingleInstanceService to enforce one app. per PC.) have it contact the server to establish an unique session. Use that to identify it for each request.
To thwart the user from 'using up' their allowance and stopping/restarting the app. (within a time limit), store some details using the PersistenceService.
You can use java.net.NetworkInterface.getNetworkInterfaces to obtain the network interfaces, and call getHardwareAddress() on them to get the MAC address.
You may want to filter out loopback with if.isLoopBack() (where "if" is the interface object). Also filter out any interface where if.getHardwareAddress() returns null. Then pick out one. You could sort them by name, if.getName(), and take the first one. For your purposes it doesn't really matter if it is the actual interface used to download your files or not, just that you can identify the computer somehow. Finally if.getHardwareAddress() gives you an array of bytes with the MAC address. If you'd rather have a String, format each byte with "%02x".format(byte) and join them with a ":" as separator.
As suggested in another answer it may be better to use PersistenceService.
Using the MAC address can however be useful if you want to persist different data for the same user on different computers in the case where the user has the same files/homedirs on each computer. You can use the MAC address as part of the URL you pass to PersistenceService#create() and get(). Useful if you want per-computer data rather than per-user data.
Short example Scala-code:
def computerID: String = {
try { // mac address of first network interface
return java.net.NetworkInterface.getNetworkInterfaces
.filter(!_.isLoopback)
.filter(_.getHardwareAddress != null)
.toList.sortBy(_.getName).head
.getHardwareAddress.map("%02x".format(_)).mkString(":")
} catch {
case _ => return "0" // no mac address available? use default "0"
}
}