📄 lhclient.java
字号:
import javax.microedition.io.*;
import java.io.*;
public class LHClient implements Runnable {
private LHCanvas canvas;
private DatagramConnection dc;
private boolean connected;
public LHClient(LHCanvas c) {
canvas = c;
connected = false;
}
public void start() {
Thread t = new Thread(this);
t.start();
}
public void run() {
try {
// Connect to the peer server
canvas.setStatus("Connecting to peer server...");
dc = null;
while (dc == null)
dc = (DatagramConnection)Connector.open("datagram://localhost:5555");
while (true) {
// Try to send a connection message
if (!connected)
sendMessage("Client");
// Try to receive a datagram packet
Datagram dg = dc.newDatagram(32);
dc.receive(dg);
// Make sure the datagram actually contains data
if (dg.getLength() > 0) {
String data = new String(dg.getData(), 0, dg.getLength());
if (data.equals("Server")) {
// Notify the user of a successful network connection
canvas.setStatus("Connected to peer server.");
connected = true;
}
else {
// Send along the network data
canvas.receiveMessage(data);
}
}
}
}
catch (ConnectionNotFoundException cnfe) {
System.err.println("The network server is unavailable.");
}
catch (IOException ioe) {
}
}
public void sendMessage(String message) {
// Send the message
try {
// Convert the string message to bytes
byte[] bytes = message.getBytes();
// Send the message
Datagram dg = null;
dg = dc.newDatagram(bytes, bytes.length);
dc.send(dg);
}
catch (Exception e) {
}
}
public void stop() {
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -