What is the benefit of creating an unconnected socket in Java? - java

In the code I'm studying, I see this line:
Socket clientSocket = new Socket();
So this is just a raw socket, connecting to nowhere? Why would you use this kind of socket that is not bound to a port?
I see on the API that it is "with the system-default type of SocketImpl."

You do this when you want to connect with a timeout:
Socket s = new Socket();
try
{
s.connect(address, timeout);
}
catch (SocketTimeoutExceptione exc)
{
// connect timeout
}

Related

How to correctly close the socket?

Client:
Open socket:
Socket socket = new Socket(host,port);
Write data:
socket.getOutputStream().write("str");
socket.getOutputStream().flush();
Read data:
response = socket.getInputStream().read();
Close connection and socket:
socket.shutdownInput();
socket.shutdownOutput();
socket.close();
Server:
Socket clientSocket = serverSocket.accept();
message = clientSocket.getInputStream().read();
clientSocket.getOutputStream().write("str2");
clientSocket.isConnected() returned true, and the server does not see that the client is disconnected. How to detect that the client is disconnected?
I'm try use this:
try {
while (true) {
message = clientSocket.getInputStream().read();
clientSocket.getOutputStream().write("str2");
}
} catch (IOException e) {
clientSocket.close();
}
But it doesn't work.
A common approach is that the client sends a "QUIT" message to the server. The server will then close it's socket.
The other approach is to do I/O on the server socket and catch the exceptions that you'll get when the client is gone.
The latter approach has a couple of drawbacks:
It will take some time for the server to give up trying to reach the client (that can take 2 minutes)
The error message might not always be the same. Usually, you'll just get a SocketException with the error message from your OS.

Listen on 9100 for print

How can i listen to raw printer port 9100 in Java.
When i create ServerSocket on port 9100 and accept connection nothing happens when i try to print to this port.
System.out.println("listening on 9100");
try {
ServerSocket serverSocket = new ServerSocket(9100);
serverSocket.setSoTimeout(0);
serverSocket.accept();
System.out.println("Accepted connection");
} catch (IOException e) {
e.printStackTrace();
}
EDIT: "Accepted connection" is never printed. So the socket is never initiated
You're ignoring the return value from serverSocket.accept().
This gives you back a socket. Seems you're not using it at all.
ServerSocket.accept
From that socket you then need to get input/output streams,
and then you can communicate with the client over these streams.

How can I get a timeout exception on an android streaming socket connection?

I've been writing an application that requires a connection to a TCP server.
I have been trying to get this section of the code to give off some sort of exception when it can't connect to the server-side port.
I know for a fact that it can't connect because I've shut down my server and the port is blocked.
Here is what I have so far:
public void run()
{
mRun = true;
try
{
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
Socket socket = new Socket(serverAddr, SERVERPORT);
try
{
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
....
In any case, my code ends up being stuck on the new Socket() constructor, and it doesn't throw any IO exceptions.
So far I've tried
socket.setSoTimeout(timeout);
but it has made no difference.
Any ideas on possible actions I can take?
try :
socket = new Socket();
socket.connect(new InetSocketAddress(serverIpAddress, serverPort), timeout);
The SO_TIMEOUT setting only affects reading from the socket, not the initial connection. You can make the connection time out by creating an unconnected socket and then using the connect method that permits a timeout parameter:
Socket socket = new Socket();
socket.connect(new InetSocketAddress(serverAddr, SERVERPORT), timeout);

How to make a SSL tcp server with java?

i'm trying to find out how to create a TCP server with SSL in java. But i don't get what i really need. Do i have to import key-files into java, and i so, how to do this? Or do i just need to change the type of the socket from Socket to SSLSocket? I've read some articles but couldn't find anything helpful because all of them just take http for communicating. I would need it for my own protocol. In my case it would be to have a program like this:
int port = 4444;
ServerSocket serverSocket = new ServerSocket(port);
System.err.println("Started server on port " + port);
// repeatedly wait for connections, and process
while (true) {
// a "blocking" call which waits until a connection is requested
Socket clientSocket = serverSocket.accept();
System.err.println("Accepted connection from client");
// open up IO streams
In in = new In (clientSocket);
Out out = new Out(clientSocket);
// waits for data and reads it in until connection dies
// readLine() blocks until the server receives a new line from client
String s;
while ((s = in.readLine()) != null) {
out.println(s);
}
// close IO streams, then socket
System.err.println("Closing connection with client");
out.close();
in.close();
clientSocket.close();
}
to use a SSL connection. So how to do this?
Thanks,
Thomas
I found this with a quick Google search.
Here.

How to find which of the first 1024 ports seem to be hosting TCP based servers on a specified host?

I want to solve my problem using and I use java programming language.
Just try to connect to them with a Socket. If you don't get a ConnectException, something is listening st that TCP port. Then do the server a favor and close the socket immediately.
What's the purpose exactly?
This is a simple code to connect to a socket with a timeout
// Create a socket with a timeout
try {
InetAddress addr = InetAddress.getByName("java.sun.com");
int port = 80;
SocketAddress sockaddr = new InetSocketAddress(addr, port);
// Create an unbound socket
Socket sock = new Socket();
// This method will block no more than timeoutMs.
// If the timeout occurs, SocketTimeoutException is thrown.
int timeoutMs = 2000; // 2 seconds
sock.connect(sockaddr, timeoutMs);
} catch (UnknownHostException e) {
} catch (SocketTimeoutException e) {
// Could not reach host - network error.
} catch (IOException e) {
// Network error
}
You can just run this code in a loop to check a series of ports.
NOTE: real portscanners are much more sophisticated: http://art-exploitation.org.ua/7261final/lib0021.html

Categories

Resources