I am trying to mark DSCP values using setTrafficClass. I have server and client set up on two different machines and I am able to print value of DSCP but I can not see it in WireShark.
I have gone through some posts online but nothing helped. I am using Windows 7 professional.
Any help would be appreciated. Thank you!
I am more testing to see how this can be done.
Here is the client code:
try {
Socket socket = new Socket(addr, 2345);
socket.setTrafficClass(10);
PrintWriter out = new PrintWriter( socket.getOutputStream(), true);
out.println("Current DSCP value: " + socket.getTrafficClass());
out.close();
socket.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
Server:
try {
ServerSocket serverSocket = new ServerSocket(1234);
Socket clientSocket = serverSocket.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
String fromClient = in.readLine();
System.out.println(fromClient);
in.close();
clientSocket.close();
serverSocket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
In console on server side:
Current DSCP value: 10
My server code and client are on separate machines.
In wireshark I see:
Differentiated Services Field: 0x00 (DSCP 0x00: Default; ECN: 0x00: Not-ECT (Not ECN-Capable Transport))
I expect to see changes in wireshark and I only see default value zero.
Last time I worked with DSCP values in Java one had to set the java.net.preferIPv4Stack system property to true due to a bug in the JVM. Othwerwise DSCP values would not be set on the underlying socket despite appearing to work in the java.net.Socket API.
Also you may have to call setTrafficClass before connecting the socket, it may not work after connection on some platforms.
java -Djava.net.preferIPv4Stack=true ...
Related
I am trying to read continuous data from TCP IP port of system using Java Socket Programming ServerSocket but I am getting unreadable string data like in following following image :
I am using following code for read data from TCP IP port :
ServerSocket server_socket;
BufferedReader input;
try {
server_socket = new ServerSocket(6666);
LOGGER.info("Server waiting for client on port "
+ server_socket.getLocalPort());
System.out.println("Server waiting for client on port "
+ server_socket.getLocalPort());
while (true) {
Socket socket = server_socket.accept();
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
try {
while (true) {
String message = input.readLine();
if (message == null) {
break;
}
}
} catch (Exception e) {
socket.close();
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
So please let me know what kind of data are in above image and what conversion I should do?
Thanks in advance.
One flaw:
The InputStreamReader is responsible for converting binary data (an InputStream) to a Reader ((Unicode) text). For that you can & should specify a text encoding, a Charset. You are using the default, platform encoding.
input = new BufferedReader(
new InputStreamReader(socket.getInputStream(), StandardCharsets.ISO_8859_1));
You can now access this server application yourself by telnet or an other terminal tool. Or even the browser by http://localhost:6666/ (telnet://localhost:6666/?).
What you are seeing does look like non-text binary data - should the default encoding not be Chinese or such.
Furthermore the code would be improved by a new thread from a thread pool handling the socket from the accept.
One should pay attention to the header lines one sends (you do not output) and then receive.
I already read some threads here on stackoverflow, also some tutorials, but I don't find a solution to my problem.
I have Java client which connects to a server, then sends exactly one line to the server, and I get 2 or 3 lines as a response.
Here is my code:
public static void main(String[] args) {
String message;
String response;
try {
BufferedReader inFromUser = new BufferedReader( new InputStreamReader(System.in));
Socket clientSocket = new Socket(hostname, port);
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
message = inFromUser.readLine();
outToServer.writeBytes(message + '\n');
// here my program "freezes"
while ((response = inFromServer.readLine()) != null) {
System.out.println("response: " + response);
}
clientSocket.close();
} catch (UnknownHostException e) {
System.out.println("Unknown Host");
} catch (IOException e) {
System.out.println("IO Exception");
}
}
My problem is, I can read every line of the response, but my program won't exit. The line clientSocket.close(); gets never called. What am I doing wrong?
Presumably your server isn't closing the connection - therefore the underlying stream for the reader isn't closed... at any point the server could send more information. readLine() only returns null when the stream has been closed, i.e. there will definitely not be any more data.
Now we don't know anything about the protocol here, but if the expected behaviour is that the client won't send any more information, and the server will close the connection, then the bug is in the server. If the protocol states that the server will keep the connection open, then the bug is in your client code and you need to work out how to detect the end of data (or send some sort of ack that will cause the server to close the connection, or whatever).
I'm trying to use telnet to request a new identity for tor. From my understanding, you're supposed to send
authenticate ""
and then if the response is "250 OK" send
signal newnym
Using this code, I get a response of "null." I have also used several telnet client libraries and get the same kind of results.
try {
Socket socket = new Socket("localhost", 9050);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("authenticate \"\"");
System.out.println(in.readLine()); //should be 250 but is null
out.close();
in.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
The documentation says that all commands are case sensitive. So you should be sending them in UPPER case (as per documentation).
I also found that a valid new identity request looks like
AUTHENTICATE
250 OK
SIGNAL NEWNYM
250 OK
Hope that helps!
Im telneting into a server and it will block the port if I do not disconnect properly. Im already using socket.close(); so I am not sure what I am doing wrong to disconnect completely from the server
//java socket client example
import java.io.*;
import java.net.*;
public class socket_client {
public static void main(String[] args) throws IOException {
Socket s = new Socket();
String host = "1.1.1.1";
PrintWriter s_out = null;
BufferedReader s_in = null;
try {
s.connect(new InetSocketAddress(host, 12656));
System.out.println("Connected");
// writer for socket
s_out = new PrintWriter(s.getOutputStream(), true);
// reader for socket
s_in = new BufferedReader(new InputStreamReader(s.getInputStream()));
}
// Host not found
catch (UnknownHostException e) {
System.err.println("Don't know about host : " + host);
System.exit(1);
}
// Send message to server
String message = "this is the msg";
s_out.println(message);
System.out.println("Message send");
// Get response from server
String response;
while ((response = s_in.readLine()) != null) {
System.out.println(response);
}
// close the socket
s.close();
// close the i/o streams
s_out.close();
s_in.close();
}
}
There is no disconnect sub-protocol in Telnet. All you have to do is close the socket.
I've never seen or heard of a Telnet server 'block a port if I do not disconnect properly'. I have a production Telnet client which does only that, and which has been working correctly for five or six years. And any server at all that doesn't handle unexpected disconnections properly has something very seriously wrong with it.
The problem is elsewhere, possibly in the (unspecified) server itself. To behave as you describe, it would have to completely ignore end of stream conditions, and ignore IOExceptions as well (or else treat them as completely fatal to the entire process). It would also have to be single-threaded. I'm finding it rather difficult to believe in the existence of such a server, or indeed this problem.
NB you only need to close 's_out', the outermost stream/writer you've wrapped around the socket output stream. If you must close the input stream and the socket, do so after closing the output stream/writer.
The socket is blocked since the server side is not handling unexpected socket closing. You have two alternatives - or rather, two steps, if you want to be thorough - to fixing this.
Handle the other end of the connection closing unexpectedly in an
exception handler, and closing the socket when needed.
Having the client send a message to the server when it wants to
close the connection, allowing the server to close the socket, and
then handling that closed socket as a successful operation.
This is an example of server socket code from O'Reilly that gracefully handles unexpected termination:
try {
ServerSocket server = new ServerSocket(5776);
while (true) {
Socket connection = server.accept( );
try {
OutputStreamWriter out
= new OutputStreamWriter(connection.getOutputStream( ));
out.write("You've connected to this server. Bye-bye now.\r\n");
connection.close( );
}
catch (IOException e) {
// This tends to be a transitory error for this one connection;
// e.g. the client broke the connection early. Consequently,
// we don't want to break the loop or print an error message.
// However, you might choose to log this exception in an error log.
}
finally {
// Most servers will want to guarantee that sockets are closed
// when complete.
try {
if (connection != null) connection.close( );
}
catch (IOException e) {}
}
}
catch (IOException e) {
System.err.println(e);
}
I have a Java TCP server which, when a client connects to it, outputs a message to the client every 30 seconds. It is a strict requirement that the client does not send any messages to the server, and that the server does not send any data other than the 30-second interval messages to the client.
When I disconnect the client, the server will not realise this until the next time it tries to write to the client. So it can take up to 30 seconds for the server to recognise the disconnect.
What I want to do is check for the disconnect every few seconds without having to wait, but I am not sure how to do this given that a) the server does not receive from the client and b) the server cannot send any other data. Would anyone please be able to shed some light on this? Thanks.
Even though your server doesn't "receive" from the client, a non-blocking read on the client socket will tell you that either there's nothing to be read (as you expect), or that the client has disconnected.
If you're using NIO you can simply use a non-blocking Selector loop (with non-blocking sockets) and only write on your 30 second marks. If a SelectionKey is readable and the read on the SocketChannel returns -1 you know the client has disconnected.
EDIT: Another approach with blocking is simply to select with a 30 second timeout. Any client disconnects will cause the select to return and you'll know which ones those are via the read set. The additional thing you'd need to do there is track how long you were blocked in the select to figure out when to do your writes on the 30 second mark (Setting the timeout for the next select to the delta).
Big Edit: After talking to Myn below, offering complete example:
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
// Set a 1 second timeout on the socket
clientSocket.setSoTimeout(1000);
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(
clientSocket.getInputStream()));
long myNextOutputTime = System.currentTimeMillis() + 30000;
String inputLine = null;
boolean connected = true;
while (connected)
{
try {
inputLine = in.readLine();
if (inputLine == null)
{
System.out.println("Client Disconnected!");
connected = false;
}
}
catch(java.net.SocketTimeoutException e)
{
System.out.println("Timed out trying to read from socket");
}
if (connected && (System.currentTimeMillis() - myNextOutputTime > 0))
{
out.println("My Message to the client");
myNextOutputTime += 30000;
}
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
}
Worth noting here is that the PrintWriter really moves you far away from the actual socket, and you're not going to catch the socket disconnect on the write (It will never throw an exception, you have to manually check it with checkError()) You could change to using a BufferedWriter instead (requires using flush() to push the output) and handling it like the BufferedReader to catch a disco on the write.
If you are managing multiple clients then I guess you would be using Non-Blocking sockets (If not then consider using Non-Blocking). You can use Selector to monitor all the connected sockets to check if they are readable or writeable or there is some Error on that socket. When some client disconnects, your Selector will mark that socket and will return.
For more help google "Socket Select function"