c4server.java

来自「J2ME手机游戏编程入门源码 16事例源码 可用手机顽童软件测试」· Java 代码 · 共 78 行

JAVA
78
字号
import javax.microedition.io.*;
import java.io.*;

public class C4Server implements Runnable {
  private C4Canvas           canvas;
  private DatagramConnection dc;
  private String             address;
  private boolean            connected;

  public C4Server(C4Canvas c) {
    canvas = c;
    connected = false;
  }

  public void start() {
    Thread t = new Thread(this);
    t.start();
  }

  public void run() {
    try {
      // Connect to the peer client
      canvas.setStatus("Waiting for peer client...");
      dc = null;
      while (dc == null)
        dc = (DatagramConnection)Connector.open("datagram://:5555");

      while (true) {
        // Try to receive a datagram packet
        Datagram dg = dc.newDatagram(32);
        dc.receive(dg);
        address = dg.getAddress();

        // Make sure the datagram actually contains data
        if (dg.getLength() > 0) {
          String data = new String(dg.getData(), 0, dg.getLength());
          if (data.equals("Client")) {
            // Notify the user of a successful network connection
            canvas.setStatus("Connected to peer client.");
            canvas.newGame();
            connected = true;

            // Try to reply with a connection message
            sendMessage("Server");
          }
          else {
            // Send along the network game data
            canvas.receiveMessage(data);
          }
        }
      }
    }
    catch (IOException ioe) {
      System.err.println("The network port is already taken.");
    }
    catch (Exception e) {
    }
  }

  public void sendMessage(String message) {
    // Send the message
    try {
      // Convert the string message to bytes
      byte[] bytes = message.getBytes();

      // Send the message
      Datagram dg = null;
      dg = dc.newDatagram(bytes, bytes.length, address);
      dc.send(dg);
    }
    catch (Exception e) {
    }
  }

  public void stop() {
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?