如下,我用NIO来处理Socket连接,下面是接受数据的代码。可是如果接受英文没有问题,如果是中文的话,就出现乱码。
/**
* 接收消息
* @param sc SocketChannel
* @return boolean
*/
private synchronized boolean acceptInfo(SocketChannel sc) {
StringBuffer sb = new StringBuffer();
ByteBuffer buffer = ByteBuffer.allocate(1024);
try {
while (sc.read(buffer) > 0) {
while (buffer.hasRemaining()) {
.....................................................
}
}
}
catch (IOException ie) {
}
}
/**
* 接收消息
* @param sc SocketChannel
* @return boolean
*/
private synchronized boolean acceptInfo(SocketChannel sc) {
StringBuffer sb = new StringBuffer();
ByteBuffer buffer = ByteBuffer.allocate(1024);
try {
while (sc.read(buffer) > 0) {
while (buffer.hasRemaining()) {
.....................................................
}
}
}
catch (IOException ie) {
}
}
String returnString = new String(data, "UTF-8");
System.out.println(returnString );
http://www.regexlab.com/zh/encoding.htm
public String receiveMessage() throws Exception {
byte[] buf = new byte[BUFSIZE];
int i = 0;
int n = 0;
while ((n = in.read()) < 0) {
//没有读进数据
//throw new IOException("epp element incomplete");
} if (i == buf.length) {
//移动数据
byte[] newBuf = new byte[buf.length + BUFSIZE];
for (int j = 0; j < buf.length; j++) {
newBuf[j] = buf[j];
}
buf = newBuf;
} //写入数据
buf[i++] = (byte) n; return new String(buf, "UTF-8").trim();
}