连接到 Jetty(超时)和 Java 的问题

问题描述 投票:0回答:0

我想与 Jetty 服务器建立连接。要求用户提供服务器地址。输入地址,然后输入他的名字。我收到一个连接超时。服务器正在运行。有人知道吗?

我有三个班级。 ChatServer、ChatClient 和 ChatWebSocket。我使用 VSCode 和 Maven

package de.patternframe.model;

import java.net.URI;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;

import javax.websocket.*;
import org.json.simple.parser.ParseException;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

@ClientEndpoint
public class ChatServer {

    private Session session;

    public void start(String address) {
        WebSocketContainer container = ContainerProvider.getWebSocketContainer();
        String uri = "ws://" + address + "/";
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter your username: ");
        String username = scanner.nextLine();
        try {
            container.connectToServer(this, new URI(uri));
            System.out.println("Connected to server " + uri);
            this.session.getBasicRemote().sendText(username);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("Connected ... " + session.getId());
        this.session = session;
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("Disconnected ... " + session.getId());
        this.session = null;
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("Error ... " + session.getId());
        throwable.printStackTrace();
        if (this.session != null) {
            this.session = null;
        }
    }
    



    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("Message from " + session.getId() + ": " + message);

        JSONParser parser = new JSONParser();
        try {
            JSONObject json = (JSONObject) parser.parse(message);
            String userName = (String) json.get("username");
            String chatMessage = (String) json.get("message");

            String timestamp = new Date().toString();
            String formattedMessage = String.format("[%s] %s: %s\n", timestamp, userName, chatMessage);

            if (this.session.isOpen()) {
                this.session.getBasicRemote().sendText(formattedMessage);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter server address: ");
        String address = scanner.nextLine();
        ChatServer server = new ChatServer();
        server.start(address);
    }
    

}
package de.patternframe.model;

import java.net.URI;
import java.util.Scanner;
import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.client.ClientUpgradeRequest;
import org.eclipse.jetty.websocket.client.WebSocketClient;
import org.json.simple.JSONObject;

public class ChatClient {

    private static String SERVER_URI = "ws://localhost:8080/";
    private static ChatWebSocket socket;

    public static void main(String[] args) {

        WebSocketClient client = new WebSocketClient();
        socket = new ChatWebSocket();
        
        try {
            client.start();
            URI serverUri = new URI(SERVER_URI);
            ClientUpgradeRequest request = new ClientUpgradeRequest();
            client.connect(socket, serverUri, request);

            Scanner scanner = new Scanner(System.in);
            System.out.print("Enter your username: ");
            String username = scanner.nextLine();
            socket.setUsername(username);
            System.out.println("Connection established with server " + SERVER_URI);
            while (true) {
                JSONObject jsonMessage = getMessage();
                socket.sendMessage(jsonMessage);
            }
        } catch (Throwable t) {
            t.printStackTrace();
        } finally {
            try {
                client.stop();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private static JSONObject getMessage() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter your message: ");
        String message = scanner.nextLine();
        JSONObject jsonMessage = new JSONObject();
        jsonMessage.put("type", "chat");
        jsonMessage.put("message", message);
        return jsonMessage;
    }
}
package de.patternframe.model;

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

@WebSocket
public class ChatWebSocket {
    private String username;
    private Session session;
    private static Set<Session> sessions = Collections.synchronizedSet(new HashSet<>());

    @OnWebSocketConnect
public void onConnect(Session session) throws IOException {
    this.session = session;
    sessions.add(session);
    this.session.getRemote().sendString("Connection established.");

    // Send the username to the server
    JSONObject jsonMessage = new JSONObject();
    jsonMessage.put("type", "username");
    jsonMessage.put("username", this.username);
    session.getRemote().sendString(jsonMessage.toJSONString());
}


    @OnWebSocketClose
    public void onClose(int statusCode, String reason) {
        System.out.println("Connection closed with statusCode=" + statusCode + ", reason=" + reason);
        sessions.remove(session);
    }

    @OnWebSocketMessage
    public void onMessage(String message) {
        JSONParser parser = new JSONParser();

        try {
            JSONObject jsonMessage = (JSONObject) parser.parse(message);
            String messageType = (String) jsonMessage.get("type");

            switch (messageType) {
                case "username":
                    this.username = (String) jsonMessage.get("username");
                    break;
                case "chat":
                    // Broadcast the chat message to all connected clients
                    broadcastMessage(this.username + ": " + jsonMessage.get("message"));
                    break;
                default:
                    System.out.println("Invalid message type.");
            }
        } catch (ParseException e) {
            System.out.println("Error parsing JSON message.");
            e.printStackTrace();
        }
    }

    public void sendMessage(JSONObject jsonMessage) throws IOException {
        this.session.getRemote().sendString(jsonMessage.toJSONString());
    }
    
    private static void broadcastMessage(String message) {
        for (Session session : sessions) {
            if (session.isOpen()) {
                try {
                    session.getRemote().sendString(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public String getUsername() {
        return this.username;
    }

    public void setUsername(String username) {
        this.username = username;
        if (session != null && session.isOpen()) {
            JSONObject jsonMessage = new JSONObject();
            jsonMessage.put("type", "username");
            jsonMessage.put("username", username);
            try {
                session.getRemote().sendString(jsonMessage.toJSONString());
            } catch (IOException e) {
                System.out.println("Error setting username.");
                e.printStackTrace();
            }
        } else {
            System.out.println("Session is null or closed. Cannot set username.");
        }
    }
}
pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>de.patternframe</groupId>
    <artifactId>loginregisterchat</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-controls</artifactId>
            <version>13</version>
        </dependency>
        <dependency>
            <groupId>org.openjfx</groupId>
            <artifactId>javafx-fxml</artifactId>
            <version>13</version>
        </dependency>
        <dependency>
             <groupId>org.openjfx</groupId>
             <artifactId>javafx-graphics</artifactId>
              <version>13</version>
        </dependency>
        <dependency>
        <groupId>com.googlecode.json-simple</groupId>
          <artifactId>json-simple</artifactId>
         <version>1.1.1</version>
        </dependency>
        
    
        <dependency>
        <groupId>org.java-websocket</groupId>
        <artifactId>Java-WebSocket</artifactId>
        <version>1.5.1</version>
         </dependency>
         <dependency>
        <groupId>javax.websocket</groupId>
        <artifactId>javax.websocket-api</artifactId>
        <version>1.1</version>
         </dependency>
         <dependency>
        <groupId>org.json</groupId>
        <artifactId>json</artifactId>
        <version>20210307</version>
         </dependency>
         <dependency>
          <groupId>com.google.code.gson</groupId>
          <artifactId>gson</artifactId>
             <version>2.10.1</version>
            </dependency>
        <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.6.1</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.6.1</version>
</dependency>
<dependency>
  <groupId>org.glassfish.tyrus</groupId>
  <artifactId>tyrus-client</artifactId>
  <version>1.10</version>
</dependency>

<dependency>
    <groupId>org.glassfish.tyrus</groupId>
    <artifactId>tyrus-server</artifactId>
    <version>1.10</version>
</dependency>
<dependency>
  <groupId>org.glassfish.tyrus</groupId>
  <artifactId>tyrus-core</artifactId>
  <version>1.10</version>
</dependency>
<dependency>
    <groupId>org.glassfish.tyrus</groupId>
    <artifactId>tyrus-container-servlet</artifactId>
    <version>1.10</version>
</dependency>
<dependency>
    <groupId>org.glassfish.tyrus</groupId>
    <artifactId>tyrus-container-grizzly-server</artifactId>
    <version>1.10</version>
</dependency>
<dependency>
    <groupId>org.eclipse.jetty.websocket</groupId>
    <artifactId>javax-websocket-server-impl</artifactId>
    <version>9.4.44.v20210927</version>
</dependency>

<dependency>
    <groupId>org.eclipse.jetty.websocket</groupId>
    <artifactId>javax-websocket-client-impl</artifactId>
    <version>9.4.44.v20210927</version>
</dependency>

<dependency>
    <groupId>org.eclipse.jetty.websocket</groupId>
    <artifactId>websocket-server</artifactId>
    <version>9.4.44.v20210927</version>
</dependency>


<dependency>
    <groupId>org.eclipse.jetty.websocket</groupId>
    <artifactId>websocket-servlet</artifactId>
    <version>9.4.44.v20210927</version>
</dependency>
<dependency>
    <groupId>org.eclipse.jetty.websocket</groupId>
    <artifactId>websocket-api</artifactId>
    <version>9.4.44.v20210927</version>
</dependency>

    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <release>11</release>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.openjfx</groupId>
                <artifactId>javafx-maven-plugin</artifactId>
                <version>0.0.6</version>
                <executions>
                    <execution>
                        <!-- Default configuration for running -->
                        <!-- Usage: mvn clean javafx:run -->
                        <id>default-cli</id>
                        <configuration>
                            <mainClass>de.patternframe.model.ChatServer</mainClass>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>
java jetty maven-jetty-plugin
© www.soinside.com 2019 - 2024. All rights reserved.