声明

这是一个Client基于J2ME以及TCP/IP协议的简单的聊天程序,在本人模拟器上测试没问题,但并不保证真机上会出现问题。

代码以及整个游戏框架你可以拿来自由使用,但请注明出处。

(一)

这部分是程序Cilent端和Server端共用的一些类,之所以把它们拿出来单独写,是为了让整个程序的框架更清晰。

其实也就一个类、一个接口,但思想是一样的,或许你需要更多的类来让Client和Server共用,举个例子来说:如果你采用了“脏矩形技术”,那么可以把每个Item、每个Frame做个共享类放在这里。

Server接口:

public interface Server {

    public static final int PORT = 8042;

}

这个接口里很简单,之定义了一个端口号,以便于以后的程序修改和维护。

Message类:

听其名字就知道了,这个是消息类,因为无论是Client端还是Server端,其消息是能抽象出很多相似的东西的。

import java.io.DataInputStream;

import java.io.DataOutputStream;

import java.io.IOException;

public class Message {

    public static final int NO_VALUE = -1;

    public static final int SIGNUP = 0;

    public static final int SIGNUP_ACK = 1;

    public static final int CLIENT_STATUS = 2;

    public static final int SERVER_STATUS = 3;

    public static final int ERROR = 4;

    public static final int SIGNOFF = 5;

    private int type;

    private String str;

    public static int player_id;

    public Message(int type,int player_id,String str) {

         this.type = type;

         Message.player_id = player_id;

         this.str = str;

    }

   

    public int getType() {

        return type;

    }

   public String getStr(){

     return str;

   }

   

    public void archive(DataOutputStream out) throws IOException {

        out.writeInt(type);

        out.writeInt(player_id);

        out.writeUTF(str);

        out.flush();

        System.out.println("***Client has send :"+type);

    }

   public static Message createFromStream(DataInputStream in) throws IOException {

        Message msg = new Message(in.readInt(), in.readInt(),in.readUTF());

        return msg;

    }

   public String toString() {

        return "Message: type # = " + type + ", player_id = "

               + player_id+", content = "+str;

    }

}

因为我们只是实现了简单的聊天功能,只是发送简单的字符给Server端,然后让其传送到各个Client端,因此功能比较简单,目的也仅仅用于学习,但你可以在此功能上增加更多的功能。