This question already has an answer here:
Address reuse not working on new Java Runtime Environment
(1 answer)
Closed 5 years ago.
Maybe I misunderstand the use of this code, but from what I understand, calling setReuseAddress(true) will allow the port to be used even if the computer still thinks it is in use.
Scenario: I have the below code. When it crashes it does not close the port, so it throws a bind error on next launch. I have used setReuseAddress(true) to try to force it to open the port, but it throws the same error. If this is the right code, how do I use it? If it's the wrong code, what will allow this behavior?
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class ServerPsswd {
public static void main(String[] args) throws IOException {
ServerSocket listener = new ServerSocket();
listener.setReuseAddress(true);
listener.bind(new InetSocketAddress(9090));
try {
while (true) {
Socket socket = listener.accept();
try {
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
out.println("tada!");
out.println("yays");
} finally {
socket.close();
}
}
}
finally {
listener.close();
}
}
}
https://docs.oracle.com/javase/7/docs/api/java/net/Socket.html#setReuseAddress(boolean)
It is to allow connections during the timeout period AFTER the current connection has been closed
Related
Hi I am currently doing a project where I have multiple clients telling the server a date however my java.util.date is not working and running me back an error message.
How would I fix this issue code is provided below as well as the message. I must also add I am writing said project in java and using the eclipse IDE.
package clientServer;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class Server {
public static void main(String[] args) throws IOException {
try (ServerSocket listener = new ServerSocket(7000)) {
System.out.println("The date server is running...");
while (true) {
try (Socket socket = listener.accept()) {
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
out.println(new Date().toString());
}
}
}
}
}
the 2 errors
for import java.util.Date it says import java.util.Date cannot be resolved
and for the code out.println(new Date()) it says Date cannot be resolved into a type
I have tried cleaning the project and using alt 5 to give it a direct path however this has not worked
i want to know the functionality of sockets in java. when i am creating some http-server i can use some ready to use sockets for secure and non-secure communication between two parties. but i never installed tomcat to my project, so my question is: how can java create a tcp / ip connection without a web-server? Can someone post me some link to clear this question?
In my case i used this to create a SSLSocket:
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import javax.net.ssl.SSLServerSocketFactory;
public class MainClass {
public static void main(String args[]) throws Exception {
SSLServerSocketFactory ssf = (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
ServerSocket ss = ssf.createServerSocket(5432);
while (true) {
Socket s = ss.accept();
PrintStream out = new PrintStream(s.getOutputStream());
out.println("Hi");
out.close();
s.close();
}
}
}
Thank u a lot,
Mira
This question already has answers here:
Java 8 Lambda function that throws exception?
(27 answers)
Closed 6 years ago.
I have the following code snippet.
package web_xtra_klasa.utils;
import java.util.Arrays;
import java.util.Properties;
import java.util.function.Function;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
public class Main {
public static void main(String[] args) throws Exception {
Transport transport = null;
try {
final Properties properties = new Properties();
final Session session = Session.getDefaultInstance(properties, null);
final MimeMessage message = new MimeMessage(session);
final String[] bcc = Arrays.asList("user#example.com").stream().toArray(String[]::new);
message.setRecipients(Message.RecipientType.BCC, Arrays.stream(bcc).map(InternetAddress::new).toArray(InternetAddress[]::new));
} finally {
if (transport != null) {
try {
transport.close();
} catch (final MessagingException e) {
throw new RuntimeException(e);
}
}
}
}
}
This does not compile because of the following error.
Unhandled exception type AddressException
I have researched a little and all the solutions were only with wrapping the checked exception in a runtime exception in a custom method. I want to avoid writing additional code for that stuff. Is there any standard way to handle such cases?
EDIT:
What I have done so far is
message.setRecipients(Message.RecipientType.BCC,
Arrays.stream(bcc).map(e -> {
try {
return new InternetAddress(e);
} catch (final AddressException exc) {
throw new RuntimeException(e);
}
}).toArray(InternetAddress[]::new));
but it does not look nice. I could swear that in one of the tutorials I have seen something standard with rethrow or something similar.
You might use some Try<T> container.
There are several already written implementations. For example:
https://github.com/javaslang/javaslang/blob/master/javaslang/src/main/java/javaslang/control/Try.java
https://github.com/hiro0107/java8-try-monad/blob/master/src/main/java/com/github/hiro0107/trymonad/Try.java
Or you can write it yourself.
I was wondering if i could get help making or finding a program that has the ability to send keyboard presses and receive them on another computer. I want to use this to play multiplayer flash-player games with friends across computers. I know there are some programs out there like "logmein" but both users cannot use the keyboard at the same time. (When i press a key the computer user cannot press a key at the same time because it wont respond.) I only know java and I am quite novice at it. Im guessing if i need to write it ill have to send the information through a port or onto a web-server. I would like to know your opinions and suggestions for this program, thanks guys.
Basically what you are looking for is a chatroom program? Have you tried looking into mIRC?
mIRC is a free internet relay chat. What exactly are the requirements for the program? Is there a certain size that it must be? Are these flash games that you and your friends are playing taking up your full computer screen?
Building a program would require a web-server(any computer with internet access would do), and you would have to open the ports on your network to allow the traffic to go through.
A basic server in java would look something like this:
Please note that after the first connection this "server" will close the connection.
import java.net.ServerSocket;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Server
{
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static BufferedReader bufferedReader;
private static String inputLine;
public static void main(String[] args)
{
// Wait for client to connect on 63400
try
{
serverSocket = new ServerSocket(63400);
while(true){
clientSocket = serverSocket.accept();
// Create a reader
bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// Get the client message
while((inputLine = bufferedReader.readLine()) != null)
{System.out.println(inputLine);}
serverSocket.close();
System.out.println("close");
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}
And a client would almost be the same:
import java.net.Socket;
import java.io.PrintWriter;
public class client
{
private static Socket socket;
private static PrintWriter printWriter;
public static void main(String[] args)
{
try
{
//change "localhost" to the ip address that the client is on, and this number to the port
socket = new Socket("localhost",63400);
printWriter = new PrintWriter(socket.getOutputStream(),true);
printWriter.println("Hello Socket");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
If I am not mistaken printWriter is a 16-bit operation, and in order to reduce lag, if you were just sending text then you might want to use printStream(). I believe that this might be a bit quicker.
I started to using mina to do async writes to the socket, but now I can't seem to close the sessions. Is there a way to force mina to close all the managed sessions or clean up? There what i have for the clean right now:
if(this.acceptor.isActive()) {
for(IoSession session : this.acceptor.getManagedSessions().values()) {
session.close(true);
}
this.acceptor.unbind();
this.acceptor.dispose();
}
Thanks
Where did you put that code?
I just used for loop like below and all sessions were closed. First, run the server and start 3 clients in 10 seconds. You will see all clients' sessions will be closed when 10 secs is up.
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
public class MinaServer {
public static void main(String[] args) throws Exception {
IoAcceptor acceptor = new NioSocketAcceptor();
acceptor.getFilterChain().addLast("logger", new LoggingFilter());
acceptor.getFilterChain().addLast(
"codec",
new ProtocolCodecFilter(new TextLineCodecFactory(Charset
.forName("UTF-8"))));
acceptor.setHandler(new ServerHandler());
acceptor.bind(new InetSocketAddress(1071));
Thread.sleep(10000);
if (acceptor.isActive()) {
for (IoSession ss : acceptor.getManagedSessions().values()) {
ss.close(true);
}
}
}
}