基于TCP/IP的手机聊天游戏(附带源码和解释)之客户端类

原创 2006年06月06日 07:10:00

客户端很简单,就是开一个线程处理用户的数据发送和接收,并做出相应的界面处理。

由于其简单,我就不再罗嗦,看代码:

MIDlet类:

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.lcdui.Alert;
import javax.microedition.lcdui.AlertType;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.MIDlet;


/**
 * @author 孙东风
 *
 **/

public class ChatMIDlet extends MIDlet implements Runnable,CommandListener{
 
    private static final String SERVER_IP = "127.0.0.1";
    private Command exit = new Command("exit",Command.EXIT,1);
    private GameScreen screen;
    private DataInputStream in;
    private DataOutputStream out;
    private StreamConnection conn;
    private boolean done;
    private int player_id;
   
    public static Display display;

    Form login_form = new Form("登陆界面");
    TextField name_textfield = new TextField("请输入呢称 :","",10,TextField.ANY);
    Command loginCommand = new Command("登陆",Command.SCREEN,1);
    static String name;
   
 public ChatMIDlet() {
  super();
  login_form.append(name_textfield);
  login_form.addCommand(loginCommand);
  login_form.setCommandListener(this);
  display = Display.getDisplay(this);
 }


 protected void startApp(){
        try {
            conn = (StreamConnection) Connector.open("socket://"+SERVER_IP+":"+Server.PORT);
            in = new DataInputStream(conn.openInputStream());
            out = new DataOutputStream(conn.openOutputStream());
        } catch (IOException e) {
            closeConnection();
            System.out.println("*** could not connect to server: " + e);
            destroyApp(true);
        }
  Display.getDisplay(this).setCurrent(login_form);
 }
 
 public DataInputStream getInput(){
  return in;
 }
 
 public DataOutputStream getOutput(){
  return out;
 }

//关闭所有资源 
    private void closeConnection() {
        try {
            if (in != null) {
                in.close();
            }

            if (out != null) {
                out.close();
            }

            if (conn != null) {
                conn.close();
            }
        } catch (IOException e) {
            System.out.println(e);
        }
    }
   

 protected void pauseApp() {

 }


 protected void destroyApp(boolean bool){
  System.out.println("MidpTestClient.destroyApp()");
  Message msg = new Message(Message.SIGNOFF, Message.NO_VALUE,null);
  try {
            msg.archive(out);
        } catch (IOException e) {
        }

        closeConnection();
        Display.getDisplay(this).setCurrent(null);
 }

 public void handleStatus(Message msg){
  GameScreen.revStr = msg.getStr();
  screen.repaint();
 }
 
 public void handleError(){
     Message msg = new Message(Message.SIGNOFF, Message.NO_VALUE,null);

        try {
            msg.archive(out);
        } catch (IOException e) {
         e.printStackTrace();
        }
 }
 
 public void handleUnknown(Message msg){
  System.out.println("received unknown message: " + msg);
 }

 public void run() {

      Message msg;

         while (!done) {
             try {
                 msg = Message.createFromStream(in);
             } catch (IOException e) {
                 System.out.println("cant read message from stream");

                 continue;
             }

             switch (msg.getType()) {
             case Message.SERVER_STATUS:
              System.out.println("Client receive SERVER_STATUS");
                 handleStatus(msg);
              break;
             case Message.ERROR:
                 handleError();
                 break;
             default:
                 handleUnknown(msg);
                 break;
             }
         }
  
 }

 public void commandAction(Command cmd, Displayable g) {
        if (cmd == exit) {
            done = true;
            destroyApp(true);
            notifyDestroyed();
        }else if(cmd == loginCommand){
         if(name_textfield.getString().length() != 0){
          name = name_textfield.getString();
          Message msg = new Message(Message.SIGNUP,Message.NO_VALUE,name_textfield.getString());
          try{
           msg.archive(out);
           msg = Message.createFromStream(in);
           if (msg.getType() != Message.SIGNUP_ACK) {
                        System.out.println("*** could not sign up: " + msg);
                        destroyApp(true);
                    }
           
                    player_id = Message.player_id;
                    System.out.println("received sign-up ack, id = " + player_id);  
                    System.out.println("--------------1");
                    screen = new GameScreen();
                    screen.initialize(this, player_id);
                    done = false;
                    Thread thread = new Thread(this);
                    thread.start();
                    Display.getDisplay(this).setCurrent(screen);
          }catch(Exception e){
           System.out.println("*** could not sign up with server: " + e);
                    destroyApp(true);
          }
         }else{
          Alert alert = new Alert("警告","用户名和密码不能为空",null,AlertType.ERROR);
       alert.setTimeout(Alert.FOREVER);
       Display.getDisplay(this).setCurrent(alert);
               }
          }
    }

}
GameScreen类:

import javax.microedition.lcdui.*;

public class GameScreen extends Canvas implements CommandListener{

 public Form message_form = new Form("Send Message Form");
 public Command sendCommand = new Command("Send",Command.OK,1);
 public Command sendCommand2 = new Command("Send",Command.OK,1);
 public TextField content_textfield = new TextField("Content :","",10,TextField.ANY);
 public String content;
 
 public static String revStr = "null";
 
 public int player_id;
 ChatMIDlet chatmidlet;

 public GameScreen(){
  message_form.append(content_textfield);
  message_form.addCommand(sendCommand2);
  message_form.setCommandListener(this);
  this.addCommand(sendCommand);
  this.setCommandListener(this);
 }

 public void initialize(ChatMIDlet midlet,int player_id){
  this.chatmidlet = midlet;
  this.player_id = player_id;
 }
 
 protected void paint(Graphics g) {
   g.setColor(0x000000);
   g.fillRect(0,0,getWidth(),getHeight());
   g.setColor(0xffffff);
   g.drawString(revStr,0,0,Graphics.LEFT|Graphics.TOP);
 }


 public void commandAction(Command cmd, Displayable g) {
  if(cmd == sendCommand){
   System.out.println("CommandListenning this");
   ChatMIDlet.display.setCurrent(message_form);
  }else if(cmd == sendCommand2){
   content = content_textfield.getString();
   Message msg = new Message(Message.CLIENT_STATUS,player_id,content);
   try{
    msg.archive(chatmidlet.getOutput());
   }catch(Exception e){
    e.printStackTrace();
    System.out.println("Send Message Failed!");
   }
   ChatMIDlet.display.setCurrent(this);
  }
 }

}

后话:希望此文能为3G到来之前吹点热风,催化催化。

效果图如下:

输入呢称并传送到Server端

输入聊天内容

显示呢称和说话内容

相关文章推荐

TCP客户端向路由器发送协议并显示回送内容、附带源码

最近做了个小项目,需要由一个Tcp客户端向路由器发送协议,并显示路由器的账号密码。网上找了一些资料,与大家一起探讨一下。下图为软件界面,长的丑了点! 最近做了个小项目,需要由一个Tcp客户端向路...

Dollars即时聊天客户端应用源码

这个源码项目是一款Dollars即时聊天客户端应用源码,源码也比较简单的,希望这个案例能够帮到大家的学习和使用。 源码下载: http://code.662p.com/view/6725.htm...

[Windows网络编程课设]南工程聊天室客户端源码

南京工程学院通信工程学院的《Windows网络编程》一课的课程设计源码,聊天室的搭构需要服务器和客户端。服务器源码请看上一篇博文,都有贴出。备注也很详细,可以参考一下。不过作为聊天室功能也很多的,我这...

Java聊天软件服务器+客户端源码---…

java最新版聊天室软件,初学项目者必备!!! 周末写的,私聊,群聊功能基本达到要求,就是服务器端的扩展功能还没优化,时间太急了,实在没心情,希望哪位大神看到后帮我改进。 聊天室服务端主要包括8个文...

Java 入门 之 聊天室 客户端源码

实现步骤 1. 开启服务器端程序; 2. 开启客户端程序; 3. 连接网络地址和网络端口; 4. 输入聊天内容,实现聊天。...

[聊天通讯] 高仿QQ源码+客户端+服务端+数据库资源齐全可编译架设外网

高仿QQ源码+客户端+服务端+数据库所有资源齐全可编译架设外网 已经可以实现注册、登陆、在线状态、查找好友、添加好友、修改个人资料、服务端增加了客户状态显示等~喜欢玩软件的朋友们可以拿去学习一下 ...

net Winform socket 套接字聊天室客户端和服务端 源码

///-------------------------------------- 客户端----------------------------------   using System; ...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:基于TCP/IP的手机聊天游戏(附带源码和解释)之客户端类
举报原因:
原因补充:

(最多只允许输入30个字)