📄 chatclient.java
字号:
package control;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import javax.microedition.lcdui.StringItem;
import clientInf.ClientInterface;
import clientInf.GameClient;
import clientInf.Sender;
import clientInf.Serializable;
import model.INFO;
import view.MidletGameHall;
/**
* Chat example for show how to use Package clientInf
* 1.create a class implements ClientInterface,besides,you need create a message class to implement the serializable interface
* 2.the class should contain a instance of GameServer
* @author sheng
*
*/
public class ChatClient implements ClientInterface{
private Sender sender=null;
private StringItem tfChat=null;
private ChatMessage chatmsg=null;
private GameClient gameclient=null;
private int chatRoomIndex;
private MidletGameHall gamehall=null;
private boolean Ready=false;
public boolean isReady() {
return Ready;
}
public ChatClient(StringItem tfChat,MidletGameHall gamehall,int chatRoomIndex,GameService gs){
Ready=false;
if(gameclient==null){
chatmsg=new ChatMessage("","","");
this.tfChat=tfChat;
this.chatRoomIndex=chatRoomIndex;
this.gamehall=gamehall;
try {
//GameService gs=new GameService();
int port = gs.getJarPort(3, chatRoomIndex);
gameclient=new GameClient(INFO.PlatformIP, port, chatmsg, this);
while (gameclient.isReady()==false){
try {
Thread.sleep(50);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
sendMessage(INFO.userAccount, "", "$REFRESH");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public void getSender(Sender sender) {
this.sender=sender;
}
public synchronized void sendMessage(String user,String time,String content){
chatmsg=new ChatMessage(user,time,content);
sender.send(chatmsg);
}
public void receiveMessage(Serializable message) {
//System.out.println(message.toString());
chatmsg=(ChatMessage)message;
if(chatmsg.content.equals("$REFRESH")){
gamehall.refreshChatTable();
return;
}
String chat=chatmsg.time+" "+chatmsg.user+":\n"+chatmsg.content+"\n";
//TODO show message
System.out.println("receice chat msg:"+chat);
tfChat.setText(chat+tfChat.getText());
}
}
class ChatMessage implements Serializable{
public String user="";
public String time="";
public String content="";
public ChatMessage(String user,String time,String content){
this.user=user;
this.time=time;
this.content=content;
}
public void deserialize(DataInputStream is) throws IOException {
user=is.readUTF();
time=is.readUTF();
content=is.readUTF();
}
public void serialize(DataOutputStream os) throws IOException {
os.writeUTF(user);
os.writeUTF(time);
os.writeUTF(content);
}
public String toString()
{
return user+" "+time+" "+content;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -