首页 > 解决方案 > 使用 Angular 和 Java 之间的 Web 套接字发送和接收数据(比如文本)

问题描述

我想建立一个后端到前端的连接来查看 UI 上的实时文本。为此,我希望 angular 作为前端,java 作为后端(现在不考虑 spring,因为我是 socketing 新手)。

通信应该是往来的……即两端应该是接收者和发送者。

我已经尝试在极客上使用https://www.geeksforgeeks.org/socket-programming-in-java/客户端和服务器。它可以工作现在我希望我的 Angular 应用程序成为接收器(使它成为发送者的帮助也会很棒)

import {AfterViewInit, Component, OnInit} from '@angular/core';
// @ts-ignore
import * as io from 'socket.io-client';


@Component({
  selector: 'app-server-component',
  templateUrl: './server-component.component.html',
  styleUrls: ['./server-component.component.scss']
})
export class ServerComponentComponent implements OnInit, AfterViewInit {

  private socket: any;


  public ngOnInit() {
    this.socket = io("http://localhost:5000");
  }

  public ngAfterViewInit() {  }

  public move(action: string) {
    this.socket.emit("move", action);
    console.log(action);
  }

}

以上日志在控制台上,但没有任何内容发送到后端。

使用如下所示的发件人时:

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;

public class Server {

  //initialize socket and input stream
  private Socket socket = null;
  private ServerSocket server = null;
  private DataInputStream in = null;

  // constructor with port
  public Server(int port) {
    // starts server and waits for a connection
    try {
      server = new ServerSocket(port);
      System.out.println("Server started");
      System.out.println("Waiting for a client ...");
      socket = server.accept();
      System.out.println("address: " + socket.getLocalPort());
      System.out.println("Client accepted");

      // takes input from the client socket
      PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
      BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

      String line = "";

      // reads message from client until "Over" is sent
      while (true) {
        try {
          System.out.println(in.readLine());
          socket.getOutputStream().write("message-backend".getBytes("UTF-8"));
        } catch (IOException i) {
          System.out.println(i);
        }
      }
      System.out.println("Closing connection");
      // close connection
      socket.close();
      in.close();
    } catch (IOException i) {
      System.out.println(i);
    }
  }

  public static void main(String args[]) { Server server = new Server(5000); }
}

以下是连接服务器时的输出,但没有任何事情发生:

服务器启动
等待客户...
地址:5000
客户接受
GET /socket.io/?EIO=3&transport=polling&t=MmAFF5Q HTTP/1.1
主机:本地主机:5000
连接:保持活动
接受: */*
来源:http://localhost:4200
用户代理:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36
引用者:http://localhost:4200/socket
接受编码:gzip、deflate、br
接受语言:en-US,en;q=0.9

标签: javascriptangularjsangularwebsocketjava-websocket

解决方案


推荐阅读