📄 chat.java
字号:
try {
String chatBuddy = TALKNAME_PREFIX + currentBuddy;
String pipeId = (String) buddyIds.get(currentBuddy);
String pipeType = isGroupChat ? "JxtaPropagate" : "JxtaUnicast";
peer.send(chatBuddy, pipeId, pipeType, m);
} catch (IOException ex) {
showAlert("Send",
"Error sending message: " + ex.getMessage(),
AlertType.ERROR,
DEFAULT_ALERT_TIMEOUT,
initForm);
return false;
}
return true;
}
private void initiateConnect() {
if (peer == null) {
peer = PeerNetwork.createInstance(tfIdentity.getString());
}
if (connected || connectInitiated) {
return;
}
connectInitiated = true;
// we will perform the actual operation in the poll thread
}
private boolean connect() {
connectInitiated = false;
String host = tfRelayHost.getString();
int port = 0;
try {
port = Integer.parseInt(tfRelayPort.getString());
} catch (NumberFormatException ex) {
showAlert("Connect",
"Error parsing relay port number: " +
tfRelayPort.getString(),
AlertType.ERROR,
DEFAULT_ALERT_TIMEOUT,
initForm);
return false;
}
String url = "http://" + host + ":" + Integer.toString(port);
if (DEBUG) {
System.out.println("Connecting to " + url + "...");
}
try {
long startTime, endTime;
if (QUANTIFY) {
startTime = System.currentTimeMillis();
}
state = peer.connect(url, state);
if (QUANTIFY) {
endTime = System.currentTimeMillis();
System.out.println("connect took " +
Long.toString(endTime-startTime));
}
connected = true;
String chatIdentity = isGroupChat ?
TALKNAME_PREFIX + currentBuddy :
TALKNAME_PREFIX + tfIdentity.getString();
if (PICSHARE_GROUPNAME.equals(currentBuddy)) {
chatIdentity = TALKNAME_PREFIX + PICSHARE_GROUPNAME;
}
String pipeType = isGroupChat ? "JxtaPropagate" : "JxtaUnicast";
String pipeId = null;
if (INSTANTP2P_GROUPNAME.equals(currentBuddy)) {
// listen on myJXTA's well-known pipe id if talking to it
pipeId = INSTANTP2P_PIPEID;
} else if (PICSHARE_GROUPNAME.equals(currentBuddy)) {
// listen on PicShare's well-known pipe id if talking to it
pipeId = PICSHARE_PIPEID;
}
if (DEBUG) {
System.out.println("Listening on " + chatIdentity);
}
peer.listen(chatIdentity, pipeId, pipeType);
int size = buddyList.size();
for (int i=0; i < size; i++) {
String buddy = buddyList.getString(i);
peer.search(PeerNetwork.PIPE, TALKNAME_PREFIX + buddy);
}
} catch (IOException ex) {
showAlert("Connect",
"Error connecting to relay: " + ex.getMessage(),
AlertType.ERROR,
Alert.FOREVER,
initForm);
return false;
}
display.setCurrent(initForm);
return true;
}
private void disconnect() {
String chatIdentity = isGroupChat ?
TALKNAME_PREFIX + currentBuddy :
TALKNAME_PREFIX + tfIdentity.getString();
if (PICSHARE_GROUPNAME.equals(currentBuddy)) {
chatIdentity = TALKNAME_PREFIX + PICSHARE_GROUPNAME;
}
String pipeType = isGroupChat ? "JxtaPropagate" : "JxtaUnicast";
String pipeId = null;
if (INSTANTP2P_GROUPNAME.equals(currentBuddy)) {
// close myJXTA's well-known pipe id if talking to it
pipeId = INSTANTP2P_PIPEID;
} else if (PICSHARE_GROUPNAME.equals(currentBuddy)) {
// close on PicShare's well-known pipe id if talking to it
pipeId = PICSHARE_PIPEID;
}
try {
peer.close(chatIdentity, pipeId, pipeType);
connected = false;
if (DEBUG) {
System.out.println("Closed " + chatIdentity);
}
} catch (IOException ex) {
showAlert("Disconnect",
"Error connecting to relay: " + ex.getMessage(),
AlertType.ERROR,
Alert.FOREVER,
initForm);
}
}
// a class to increment the value of a Gauge everytime it is run
static class StatusUpdate extends TimerTask {
private StringItem elapsed = null;
private Gauge status = null;
private int tick = 0;
private int max = 0;
StatusUpdate(StringItem elapsed, Gauge status) {
this.elapsed = elapsed;
this.status = status;
max = status.getMaxValue();
}
public void run() {
elapsed.setText(Integer.toString(++tick) + "s");
status.setValue(tick % max);
}
}
public void run() {
if (DEBUG) {
System.out.println("starting poll thread");
}
while (!stopPolling) {
if (!connected && connectInitiated) {
Form connectingForm = new Form("Connecting...");
StringItem elapsed = new StringItem("", null);
connectingForm.append(elapsed);
Gauge status = new Gauge(null, false, 10, 0);
connectingForm.append(status);
display.setCurrent(connectingForm);
StatusUpdate updater = new StatusUpdate(elapsed, status);
new Timer().scheduleAtFixedRate(updater, 1000, 1000);
try {
connect();
} finally {
updater.cancel();
display.setCurrent(initForm);
connectingForm = null;
}
if (sendPending) {
try {
send();
} finally {
sendPending = false;
}
}
}
try {
// keep polling until we drain all queued messages
while (poll()) {
}
} catch (Throwable t) {
showAlert("Poll",
"Error processing message: " + t.getMessage(),
AlertType.ERROR,
DEFAULT_ALERT_TIMEOUT,
initForm);
}
try {
// poll interval is specified in seconds
Thread.currentThread().sleep(pollInterval * 1000);
} catch (InterruptedException ignore) {
}
}
if (DEBUG) {
System.out.println("stopped poll thread");
}
}
private boolean poll() {
if (peer == null || !connected) {
// not yet connected
return false;
}
Message msg = null;
try {
long startTime, endTime;
if (QUANTIFY) {
startTime = System.currentTimeMillis();
}
// timeout must not be zero: zero means block forever
if (peer != null) {
msg = peer.poll(1);
}
if (QUANTIFY) {
endTime = System.currentTimeMillis();
System.out.println("poll took " +
Long.toString(endTime-startTime));
}
} catch (IOException ex) {
showAlert("Poll",
"Error polling relay: " + ex.getMessage(),
AlertType.ERROR,
DEFAULT_ALERT_TIMEOUT,
initForm);
return false;
}
if (msg == null) {
return false;
}
Element el = null;
String name = null;
String id = null;
for (int i=0; i < msg.getElementCount(); i++) {
el = msg.getElement(i);
if (Message.PROXY_NAME_SPACE.equals(el.getNameSpace())) {
String elementName = el.getName();
if (Message.NAME_TAG.equals(elementName)) {
name = new String(el.getData());
} else if (Message.ID_TAG.equals(elementName)) {
id = new String(el.getData());
}
}
}
if (name != null) {
if (name.indexOf(TALKNAME_PREFIX) >= 0) {
name = name.substring(TALKNAME_PREFIX.length());
}
int size = buddyList.size();
for (int i=0; i < size; i++) {
String buddy = buddyList.getString(i);
if (buddy.equals(name) &&
id != null && !"".equals(id)) {
buddyIds.put(name, id);
break;
}
}
}
String sender = null;
String message = null;
String imageCaption = null;
String imageFileName = null;
byte[] imageData = null;
boolean isDisplayable = true;
for (int i=0; i < msg.getElementCount(); i++) {
el = msg.getElement(i);
if ("JxtaTalkSenderName".equals(el.getName())) {
sender = new String(el.getData());
} else if ("JxtaTalkSenderMessage".equals(el.getName())) {
message = new String(el.getData());
} else if ("Caption".equals(el.getName())) {
imageCaption = new String(el.getData());
} else if ("FileName".equals(el.getName())) {
imageFileName = new String(el.getData());
} else if ("DataBlock".equals(el.getName())) {
imageData = el.getData();
isDisplayable = false;
}
if (DEBUG) {
System.out.print(i + " " + el.getName());
if (isDisplayable) {
System.out.print(" " + new String(el.getData()));
}
System.out.println();
}
isDisplayable = true;
}
if (imageData != null) {
String caption =
imageCaption == null ? imageFileName : imageCaption;
imageCanvas.createImage(imageData, caption, sender);
display.setCurrent(imageCanvas);
}
if (sender != null && message != null) {
if (sender.indexOf(TALKNAME_PREFIX) >= 0) {
sender = sender.substring(TALKNAME_PREFIX.length());
}
replyBuddy = sender;
String displayedMsg = sender + "> " + message + "\n";
// keep the last DEFAULT_SCROLL messages, the rest scroll off
StringItem si = new StringItem(null, displayedMsg);
if (initForm.size() >= DEFAULT_SCROLL) {
initForm.delete(0);
}
initForm.append(si);
// pop an alert for a millisecond to get a notification beep
showAlert("", "", AlertType.INFO, 1, initForm);
}
return true;
}
private void showAlert(String title, String message, AlertType type,
int timeout, Displayable back) {
Alert alert = new Alert(title, message, null, type);
alert.setTimeout(timeout);
display.setCurrent(alert, back);
}
private static class ImageCanvas extends Canvas
{
Image image = null;
String caption = null;
String sender = null;
Chat midlet = null;
int width = 0;
int height = 0;
int lineHeight = 0;
ImageCanvas(Chat midlet) {
this.midlet = midlet;
width = getWidth();
height = getHeight();
lineHeight = Font.getDefaultFont().getHeight();
}
public void createImage(byte[] data, String caption, String sender) {
this.caption = caption;
this.sender = sender;
try {
image = Image.createImage(data, 0, data.length);
repaint();
} catch (Exception ex) {
System.out.println(ex);
}
}
public void paint(Graphics g) {
// clear
g.setColor(255, 255, 255);
g.fillRect(0, 0, width, height);
g.setColor(0, 0, 0);
if (image != null) {
int xoff = width / 2;
int yoff = height / 2;
g.drawImage(image, xoff, yoff,
Graphics.VCENTER | Graphics.HCENTER);
}
if (caption != null) {
g.drawString(caption, 0, 0,
Graphics.TOP | Graphics.LEFT);
}
if (sender != null) {
g.drawString(sender, 0, height,
Graphics.BOTTOM | Graphics.LEFT);
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -