I can't disconnect my socket.io test server - java

I try to disconnect my client:
public class SiecZapis {
public static Socket gniazdo2;
public static void main(String[] args) {
new SiecZapis().doIt2();
}
public void doIt2() {
try {
ServerSocket gniazdo = new ServerSocket(4242);
while(true) {
Socket gniazdo2 = gniazdo.accept();
PrintWriter pisarz = new PrintWriter(gniazdo2.getOutputStream());
String porada = "test2";
pisarz.println(porada);
pisarz.close();
System.out.println(porada);
}
} catch(Exception ex) {
ex.printStackTrace();
}
}
public void exit() {
gniazdo2.disconnect();
}
}
I tried to use something like socket.disconnect() from this topic but there is not method disconnect in socket.
Could you please advise how to handle this topic?

Insted of disconnect try using the close method.
public void exit(){
gniazdo2.close();
}
Further reading: https://docs.oracle.com/javase/8/docs/api/java/net/Socket.html#close--

Related

How do I close a multithreaded server?

So I have a program that clients can enter any type of tasks and other clients can check it as well but I don't know how to close the loop that tries to accept new connetions to the server.
What I want is when I close the last client running using a command I wrote I want the server to close as well.
Can anyone help?
public class TaskListServer {
public static List<String> taskList = new ArrayList<>();
public static String uniqueString(){
return String.join(", ", taskList);
}
public static void addTasks(String task) {
taskList.add(task);
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
ServerSocket serverSocket = new ServerSocket(4242);
while (true) {
Socket clientSocket = serverSocket.accept();
ThreadedServer clientThread = new ThreadedServer(clientSocket);
new Thread(clientThread).start();
}
}catch (IOException e) {
e.printStackTrace();
}
sc.close();
}
Don't use an infinity loop (while(true)).
private static boolean acceptNewClients = true;
public static void flipAcceptNewClients() {
acceptNewClients = !acceptNewClients;
}
public static void main(String[] args) {
/* your code here */
while (acceptNewClients) {
Socket clientSocket = serverSocket.accept();
ThreadedServer clientThread = new ThreadedServer(clientSocket);
new Thread(clientThread).start();
}
/* your code here */
}

why java tcp server is accepting closed socket?

I have a class A that accepts TCP connection and send this new socket to Thread B where data from that socket is received and sent.
Class A{
Class b = new B();
public void run()
{
b.start();
while(true){
Socket socket = serverSocket.accept();
if(socket==null || socket.isClosed())continue;
b.setSocket(socket);
}
}
}
Class B extends Thread{
Socket socket;
public void setSocket(Socket p_socket) throws IOException
{
if(socket!=null && !socket.isClosed())
{
try{
socket.close();
socket = null;
Thread.sleep(5);
}
catch(Exception ex)
{}
}
socket = p_socket;
inputStream = socket.getInputStream(); // Here I am getting socket.closed() exception very much.
}
This worked fairly good in the past but now recently I am very very frequently getting the following error.
java.io.IOException: Socket Closed
at java.net.AbstractPlainSocketImpl.getInputStream(AbstractPlainSocketImpl.java:421)
at java.net.Socket$2.run(Socket.java:914)
at java.net.Socket$2.run(Socket.java:912)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.Socket.getInputStream(Socket.java:911)
I don't understand why this is happening now after years of working fine. Is this due to the network problem or Thread related something?
Updated:
Can this be the server related problem? Because the same application is running on other server but they are not having this problem.
The whole setup concept looks a bit broken. You should not "change" resources from the outside, while maybe there is still some work going on in that thread. A way better concept is to encapsulate the Socket into a new worker thread:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
public class WrapHandler {
static public class Server {
private final ServerSocket mSocket;
private final ArrayList<Handler> mRunningHandlers = new ArrayList<>();
public Server(final int pPort) throws IOException {
mSocket = new ServerSocket(pPort);
new Thread(() -> mainLoop()).start();
}
private void mainLoop() {
while (true) {
try {
#SuppressWarnings("resource") final Socket socket = mSocket.accept(); // do not close, do not handle with resource, socket will be closed by handler!
final Handler h = new Handler(socket, this);
handlerStarted(h);
} catch (final IOException e) {
e.printStackTrace(); // do something useful
}
}
}
synchronized void handlerStarted(final Handler pHandler) {
mRunningHandlers.add(pHandler);
}
synchronized void handlerEnded(final Handler pHandler) {
mRunningHandlers.remove(pHandler);
}
void handleException(final Handler pHandler, final Throwable pException) {
/* again do something useful */
}
}
static public class Handler {
private final Socket mSocket;
private final Server mServer;
public Handler(final Socket pSocket, final Server pServer) {
mSocket = pSocket;
mServer = pServer;
new Thread(() -> handleSocket()).start();
}
private void handleSocket() {
try {
handleData();
} catch (final IOException e) {
mServer.handleException(this, e);
} finally {
mServer.handlerEnded(this);
stop();
}
}
private void handleData() throws IOException {
mSocket.getInputStream().read();
/* data handling code here */
}
void stop() {
try {
mSocket.close();
} catch (final IOException e) { /* ignore or handle as you will */ }
}
}
}

My client wont connect to its server

I have made Client.java and Server.java. Here they are below.
Client
public class Client
{
ClientConnection cc;
public static void main(String[] args)
{
new Client();
}
public Client()
{
try
{
Socket s = new Socket("localhost",4444);
cc = new ClientConnection(s,this);
cc.start();
listenForInput();
} catch (UnknownHostException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
}
public void listenForInput(){
Scanner console = new Scanner(System.in);
while(true){
while(!console.hasNextLine()){
try
{
Thread.sleep(10);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
String input = console.nextLine();
cc.sendStringToServer(input);
}
}
}
Server
public class Server
{
ServerSocket ss;
ArrayList<ServerConnection> connections = new ArrayList<ServerConnection>();
boolean shouldRun = true;
ServerWindow serverWindow;
public static void main(String[] args)
{
new Server();
}
public Server(){
try
{
serverWindow= new ServerWindow();
serverWindow.setVisible(true);
ss = new ServerSocket(4444);
serverWindow.serverLog("Server starting");
while(shouldRun){
Socket s = ss.accept();
ServerConnection sc = new ServerConnection(s,this);
sc.start();
connections.add(sc);
serverWindow.serverLog("A client connected from " + sc.getIP());
}
} catch (IOException e)
{
e.printStackTrace();
}
}
public ServerWindow getServerWindow(){
return serverWindow;
}
}
When i run Client.java and Server.java they connect fine and carry out their tasks as expected. But when I am in a new class and i create a client object and a server object, the client doesnt work properly.
public class tester
{
public static void main(String[] args)
{
Server server = new Server();
Client client = new Client();
client.cc.sendStringToServer("From tester");
}
}
The server works fine, it creates the window as expected but the client object doesnt work. My server object will not recognize a connection like it does when it normally works and my client's message will not go through. What am I missing? Does it have to do with using localhost as the ip?
Your problem is that you block the main thread by calling
listenForInput();
in your Client. Create a new Thread that calls the input listener and you will be fine.
new Thread(new Runnable() {
public void run() {
listenForInput();
}
}).start();
Edit: The same problem is in the Server class. There is an infinite loop, that blocks the Server constructor from finishing. Also add this:
new Thread(new Runnable() {
public void run() {
while(shouldRun) {
Socket s = ss.accept();
// do other stuff
}
}
}).start();
Note: You do not need to sleep the thread when waiting for input. Just write some empty brackets or a semicolon.
while (!console.hasNextLine()) ;

Java Socket Handling Clients Disconnecting [duplicate]

This question already has answers here:
Java socket API: How to tell if a connection has been closed?
(9 answers)
Closed 7 years ago.
i am trying to make a chat program. The problem i am having is that my loop in the EchoThread always thinks that the connection is true. I have tried to use if(s.isConnected() == false) but that didn't work also i tried to do if(s.isClosed() == true) if you can help thank you in advance. Here is my code
import java.io.*;
import java.net.*;
import java.util.ArrayList;
public class server {
public ObjectInputStream input;
public ServerSocket server;
public Socket s;
public ObjectOutputStream output;
public ArrayList<ObjectOutputStream> outputs = new ArrayList<ObjectOutputStream>();
public ArrayList<Socket> users = new ArrayList<Socket>();
public class Accept implements Runnable {
public void run() {
try {
server = new ServerSocket(55555, 100);
} catch (IOException e) {
e.printStackTrace();
}
while(true) {
try {
s = server.accept();
new EchoThread(s).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class EchoThread extends Thread {
private Socket s1;
public EchoThread(Socket s) throws IOException {
this.s1 = s;
}
public void run() {
users.add(s1);
try {
outputs.add(new ObjectOutputStream(s1.getOutputStream()));
newUser();
} catch (IOException e) {
System.out.println("Error 2");
}
while(s1.isConnected() == true) {
// loops until socket looses connection
}
System.out.println("Disconnected");
}
}
public class check implements Runnable {
public void run() {
}
}
public void newUser() {
try {
for(ObjectOutputStream o: outputs) {
o.writeObject(s.getInetAddress() + " Connected");
}
} catch (IOException e1) {
System.out.println("Error 21");
}
}
server() throws IOException {
Thread t = new Thread(new Accept());
t.start();
Thread ch = new Thread(new check());
ch.start();
}
public static void main(String[] args) throws IOException {
new server();
}
}
you have to read this, you have to check with the read()method to check if it returns -1.
https://stackoverflow.com/a/10241044/964152
while(s1.isConnected() == true) {
This is not a valid loop. isConnected() is true because you accepted the socket, and it doesn't magically become false afterwards. When the client disconnects, you will get the appropriate end of stream indication from whichever read method you're calling.

Websocket server.run() don't allow followed codes to start

I have the following web-socket server code from (https://github.com/TooTallNate/Java-WebSocket):
public class WebsocketServer extends WebSocketServer {
private static int PORT = 2005;
private Set<WebSocket> conns;
public WebsocketServer() {
super(new InetSocketAddress(PORT));
conns = new HashSet<>();
}
#Override
public void onOpen(WebSocket conn, ClientHandshake handshake) {
conns.add(conn);
System.out.println("New connection from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
}
#Override
public void onClose(WebSocket conn, int code, String reason, boolean remote) {
conns.remove(conn);
System.out.println("Closed connection to " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
}
#Override
public void onMessage(WebSocket conn, String message) {
System.out.println("Received: " + message);
for (WebSocket sock : conns) {
sock.send(messageToSend);
}
}
#Override
public void onError(WebSocket conn, Exception ex) {
ex.printStackTrace();
if (conn != null) {
conns.remove(conn);
// do some thing if required
}
System.out.println("ERROR from " + conn.getRemoteSocketAddress().getAddress().getHostAddress());
}
public static void main(String[] args) throws IOException, InterruptedException {
WebsocketServer server = new WebsocketServer();
server.run();
BufferedReader sysin = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String in = sysin.readLine();
server.sendToAll(in);
if (in.equals("exit")) {
server.stop();
break;
} else if (in.equals("restart")) {
server.stop();
server.start();
break;
}
}
}
public void sendToAll(String text) {
Collection<WebSocket> con = connections();
synchronized (con) {
for (WebSocket c : con) {
c.send(text);
}
}
}
}
The codes works fine, but all codes that comes after server.run(); won't start/work! that part I need to send messages from Java console to client.
What I am doing wrong?
Note: My client works in JavaScript and can connect to the server
You need to start() Runnable class, not run() it directly
server.start();
instead of
server.run();

Categories

Resources