📄 mailconnection.java
字号:
import javax.microedition.io.SocketConnection;
import javax.microedition.io.Connector;
import java.io.;
/**
* 该类实现了到邮件服务器的连接,提供了send、receive等方法。
*/
public class MailConnection {
//
private static final byte CR = 0x0D; //回车
private static final byte LF = 0x0A; //换行
private static final byte[] CRLF = {CR, LF};
private SocketConnection socket; //套接字
private OutputStream os;
private InputStream is;
private byte[] buffer = new byte[128]; //读取数据的缓冲区
//构造方法,创建一个到host:port的套接字连接
public MailConnection(String host, int port) throws IOException {
socket = (SocketConnection)Connector.open("socket://" + host + ":" + port);
os = socket.openOutputStream();
is = socket.openInputStream();
}
//关闭连接
public void close() throws IOException {
if(socket != null) {
socket.close();
socket = null;
}
}
//检测是否连接到服务器
public boolean isConnection() {
return socket != null;
}
//发送字符串s到服务器
public void send(String s) throws IOException {
byte[] bytes = s.getBytes();
int len = bytes.length;
if(len == 0) {
os.write(CRLF, 0, 2);
}
else {
int i = 0;
int j = i;
while(i < len) {
while(j<len && bytes[j] != CR && bytes[j] != LF) {
j++;
}
os.write(bytes, i, j-i);
os.write(CRLF, 0, 2);
if(j < len-1 && bytes[j] == CR && bytes[j+1] == LF) {
j++;
}
i = ++j;
}
}
}
//接收服务器返回的字符串,字符串以CRLF为结束标志。
public String receive() throws IOException {
boolean stop = false;
int n = -1;
StringBuffer result = new StringBuffer();
while(!stop) {
int count = 0;
while(true) {
n = is.read(buffer, count, 1); //读取一个字节
if(n == -1) { //
try {
close(); //关闭连接
}
catch(IOException ioe) {
//
}
throw new IOException("连接已经关闭");
}
else if(n == 0) {
Thread.yield();//暂停当前线程,其他线程获得执行的机会。
}
else { //
byte b = buffer[count];
if(b == CR) {
//忽略CR
}
else if(b == LF) { //遇到结束标志,停止读取数据
stop = true;
break;
}
else {
count++; //接收读取的字节
if(count>=buffer.length) { //缓冲区满
break;
}
}
}
}
result.append(new String(buffer, 0, count));
}
return result.toString();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -