I have some problems with my server socket. I create a DatagramSocket to chat between a server and a client.
public static void main (String[] args) throws IOException {
byte[] send = new byte[1024];
byte[] receive = new byte[1024];
BufferedReader entree;
DatagramSocket serverSocket = null;
InetAddress ip;
InetAddress ipDest;
int port;
try {
serverSocket = new DatagramSocket(8888);
} catch (SocketException e) {
e.printStackTrace();
}
while (true) {
DatagramPacket recu = new DatagramPacket(receive, receive.length);
serverSocket.receive(recu);
String sentence = new String(recu.getData());
ipDest = recu.getAddress();
port = recu.getPort();
System.out.println("Reçu:"+sentence);
entree = new BufferedReader(new InputStreamReader(System.in));
String chaine = entree.readLine();
send = chaine.getBytes();
DatagramPacket dp = new DatagramPacket(send, send.length, ipDest, port);
serverSocket.send(dp);
send = new byte[1024];
receive = new byte[1024];
}
But I use new BufferedReader(new InputStreamReader(System.in))
get the next stuff to send, and it is blocking. So, I cannot receive what's comming from the client and print it.
How can I arrange this ?
Merci, eo
Trying to do non-blocking reads on System.in
in Java is an exercise in futility. There's no portable way to do it, so Java doesn't support it.
Even if you create a separate thread and do a blocking read there, you'll have the problem of that thread being non-interruptible. See: Java: how to abort a thread reading from System.in
Basically, you either need to use a platform specific library (JNI) ( JCurses for linux, for example), or use a GUI.
Edit to add: What you can do is move your socket reading to a different thread, as that is interruptible.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.