与Java套接字编程一起使用的观察者模式不起作用 [英] Observer Pattern used with Java socket programing not working

查看:88
本文介绍了与Java套接字编程一起使用的观察者模式不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试根据来自服务器的数据更新客户端视图时,我的Observer模式出现问题.

I have a problem with my Observer pattern when I'm trying to update the client view based on the data that comes from the server.

将消息发送到客户端的代码:

The code that sends messages to the client:

package model;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class PlayerThread extends Thread{
private BufferedReader inFromClient;
private PrintWriter outToClient;
private Socket socket;

public PlayerThread(Socket socket) throws IOException{
    this.socket = socket;
    inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    outToClient = new PrintWriter(socket.getOutputStream(), true);

    outToClient.println("Hey");
}

public void run(){
    // needs to be implemented
}
}

负责在客户端接收数据的代码:

The code that takes care of recieving data on the client side:

package connection;

import java.io.BufferedReader;

import mediator.ModelManager;

public class ClientRecieverThread extends Thread {

private ModelManager model;
private BufferedReader inFromServer;

public ClientRecieverThread(ModelManager model, BufferedReader inFromServer) {
    this.model = model;
    this.inFromServer = inFromServer;
}

@Override
public void run() {

    String message = null;
    try {
        while (true) {
            message = inFromServer.readLine();
            //System.out.println(message);
            model.setMessage(message);
        }
    } catch (Exception e) {

    }
}

}

以及包含我在客户端使用的观察者模式的代码:

and the code that contains the observer pattern that I use on the client side:

package model;
public class MessageHandler {
private String message;

public MessageHandler(){
    message = "Welcome";
}

public void setMessage(String message){
    this.message = message;
}

public String getMessage(){
    return this.message;
}
}

package mediator;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.Observable;

import model.MessageHandler;
import connection.Proxy;

public class ModelManager extends Observable{
private MessageHandler messageHandler;
private Proxy proxy; // establish the connection with the server

public ModelManager() throws UnknownHostException, IOException{
    proxy = new Proxy(this);
    messageHandler = new MessageHandler();
}

public synchronized void setMessage(String message){
    setChanged();
    messageHandler.setMessage(message);
    notifyObservers(message);
}

public String getMessage(){
    return messageHandler.getMessage();
}

public void send(String message){
    proxy.send(message);
}
}



package view;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.Observable;
import java.util.Observer;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

import model.Board;

public class View extends JPanel implements Observer{
private JFrame frame;
private Board board;
private Rectangle[][] squares;
private JLabel messageLabel;

public View(){
    initComponents();
    initVariables();
    addComponents();
}

private void initComponents() {
    frame = new JFrame("TicTacToe");
    frame.setSize(500, 500);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);

    messageLabel = new JLabel("");
    messageLabel.setHorizontalAlignment(SwingConstants.CENTER);
    messageLabel.setVerticalAlignment(SwingConstants.CENTER);

    this.setSize(300,300);
    }

private void initVariables() {
    board = new Board(3,3, 100);

    squares = new Rectangle[board.getRow()][board.getCol()];
    for (int i = 0; i < squares.length; i++){
        for (int j = 0; j < squares[i].length; j++){
            squares[i][j] = new Rectangle();
        }
    }
}

private void addComponents() {
    frame.add(messageLabel, BorderLayout.NORTH);
    frame.add(this);

    frame.setVisible(true);
}


private void drawBoard(Graphics g, Board board) {
    int positionX = this.getWidth()/2 - (board.getCellSize() + board.getCellSize()/2);
    int positionY = 50;

    Graphics2D g2d = (Graphics2D) g;

    for (int i = 0; i < board.getRow(); i++) {
        for (int j = 0; j < board.getCol(); j++) {

            squares[i][j] = new Rectangle(positionX, positionY, 100, 100);
            positionX += 100;

            g2d.draw(squares[i][j]);
        }
        positionY += board.getCellSize();
        positionX = this.getWidth()/2 - (board.getCellSize() + board.getCellSize()/2);
    }
}

public void paintComponent(Graphics g){
    drawBoard(g, board);
}


public void update(Observable o, Object arg) {
    System.out.println((String)arg);
}


}

ModelManagerView之间的连接是在Controller类中完成的,就像这样(model.addObserver(view));

The connection between the ModelManager and the View is done in the Controller class like this (model.addObserver(view));

问题是,尽管客户端已接收到数据,但我不理解为什么视图无法更新.

The prolem is that I don't understand why the view doesn't get updated, although the data gets recieved by the client.

先谢谢您! :)

推荐答案

更改模型时,需要调用方法notifyObservers();,这将通知已添加到模型的观察者.

You need to call the method notifyObservers(); when the model is changed, this is will notify the observers added to the model.

因此在setMessage(String message)内部,进行编码:

So inside the setMessage(String message), do the coding:

if(this.message!=message){
   this.message = message;
   notifyObservers();
}

这篇关于与Java套接字编程一起使用的观察者模式不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆