当前位置: 首页 > news >正文

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

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

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

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端

输入聊天内容

显示呢称和说话内容

相关文章:

  • 在DataGrid等控件中添加自动编号的列
  • java 循环队列实现_Java实现循环队列
  • 长期用电脑人士要多吃樱桃
  • [软工]此EUP非彼EUP
  • java 加减乘除是原子操作吗_Go并发编程之传统同步—(3)原子操作
  • 毕业了
  • mysql innodb 删除_MySQL InnoDB 删除资料后释放硬盘空间
  • request变量java jsp_JSP里request变量列表
  • transition java_Transition 过渡
  • 相对最完整的软件测试工具手册
  • 上传图片并且生成可以控制大小图片清晰度的方法
  • 手机php开发环境,PHP开发环境搭建
  • 要不要把php5升级到php7,将php5升级到php7后AJAX不工作
  • [软工]近距离接触RUP plug-in
  • zblog asp 转 php,怎么把zblog asp 2.2转换成zblog php 1.5的方法
  • Docker 笔记(2):Dockerfile
  • JavaScript 是如何工作的:WebRTC 和对等网络的机制!
  • jQuery(一)
  • js 实现textarea输入字数提示
  • MySQL用户中的%到底包不包括localhost?
  • Python打包系统简单入门
  • Quartz实现数据同步 | 从0开始构建SpringCloud微服务(3)
  • Transformer-XL: Unleashing the Potential of Attention Models
  • 阿里云购买磁盘后挂载
  • 高性能JavaScript阅读简记(三)
  • 湖南卫视:中国白领因网络偷菜成当代最寂寞的人?
  • 扫描识别控件Dynamic Web TWAIN v12.2发布,改进SSL证书
  • 腾讯优测优分享 | Android碎片化问题小结——关于闪光灯的那些事儿
  • 温故知新之javascript面向对象
  • Python 之网络式编程
  • Unity3D - 异步加载游戏场景与异步加载游戏资源进度条 ...
  • 机器人开始自主学习,是人类福祉,还是定时炸弹? ...
  • 如何用纯 CSS 创作一个菱形 loader 动画
  • #if 1...#endif
  • #经典论文 异质山坡的物理模型 2 有效导水率
  • #周末课堂# 【Linux + JVM + Mysql高级性能优化班】(火热报名中~~~)
  • (02)vite环境变量配置
  • (1)Android开发优化---------UI优化
  • (LNMP) How To Install Linux, nginx, MySQL, PHP
  • (Matlab)遗传算法优化的BP神经网络实现回归预测
  • (Redis使用系列) SpirngBoot中关于Redis的值的各种方式的存储与取出 三
  • (九)One-Wire总线-DS18B20
  • (理论篇)httpmoudle和httphandler一览
  • (转)真正的中国天气api接口xml,json(求加精) ...
  • ******之网络***——物理***
  • *ST京蓝入股力合节能 着力绿色智慧城市服务
  • .bat批处理(三):变量声明、设置、拼接、截取
  • .NET : 在VS2008中计算代码度量值
  • .net core 6 redis操作类
  • .net core 6 使用注解自动注入实例,无需构造注入 autowrite4net
  • .net core webapi 大文件上传到wwwroot文件夹
  • .NET/ASP.NETMVC 大型站点架构设计—迁移Model元数据设置项(自定义元数据提供程序)...
  • .NET下的多线程编程—1-线程机制概述
  • .Net转Java自学之路—SpringMVC框架篇六(异常处理)
  • /etc/motd and /etc/issue