我刚接触 socket 找了本书,练习了一下,现在有几点不明白
网上一些例子写的都是长连接,客户端都是连接了一次,如果在连接期间,服务端关闭,怎么样让客户端定时每隔几秒连一次,直到服务端再打开?
我参考的客户端代码如下
import java.net.*;
import java.nio.channels.*;
import java.nio.*;
import java.io.*;
import java.nio.charset.*;
import java.util.*;public class SocketClient {
private static SocketChannel socketChannel = null;
private int serverPort = 10000;
private ByteBuffer sendBuffer = ByteBuffer.allocate(1024);
private ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);
private Charset charset = Charset.forName("UTF-8");
private Selector selector;
private static boolean flag; public SocketClient() throws IOException {
socketChannel = SocketChannel.open();
InetAddress ia = InetAddress.getLocalHost();
InetSocketAddress isa = new InetSocketAddress(ia, serverPort);
try {
flag = socketChannel.connect(isa);
socketChannel.configureBlocking(false);
System.out.println("与服务器的连接建立成功");
selector = Selector.open();
} catch (SocketException ex) {
System.out.println("connect error");
return;
}
}
public static void main(String args[]) throws IOException {
final SocketClient client = new SocketClient();
flag = socketChannel.isConnected();
if(flag){
Thread receiver = new Thread() {
public void run() {
client.receiveFromUser();
}
}; receiver.start();
client.talk();
}else{
//重新连
--------------此段很模糊 自己乱加的--------
Thread receiver2 = new Thread() {
public void run() {
try {
client.reConnect(flag);
} catch (IOException ex) {
}
}
};
receiver2.start();
---------------------------------------
}
}
//重新连接
public static void reConnect(boolean flag) throws IOException {
while(!flag){
// timer.schedule(new TimerTask() {
// public void run() {
// start();
// timer.cancel();
// }
// public void start() {
// try {
new SocketClient();
// } catch (IOException ex) {
// }
// }
// }, 6000, 6000);
flag = socketChannel.isConnected();
}
------------连是连上了,可是得建立talk,还得用线程,可是线程里的对象一定是final的,所以等于连了两次----
if (flag) {
final SocketClient client2 = new SocketClient();
Thread receiver = new Thread() {
public void run() {
client2.receiveFromUser();
}
};
receiver.start();
client2.talk();
}
------------------------------------------------
} public void receiveFromUser() {
try {
BufferedReader localReader = new BufferedReader(new InputStreamReader(
System.in));
String msg = null;
while ( (msg = localReader.readLine()) != null) {
if ( msg.length() < 1) {
System.out.println("null");
msg = "syn";
} synchronized (sendBuffer) {
sendBuffer.put(encode(msg + "\r\n"));
} if (msg.equals("echo:bye")) {
System.out.println("关闭");
break;
}
if (msg.equals("bye")) {
System.out.println("关闭");
break;
}
}
}
catch (IOException e) {
e.printStackTrace();
}
} public void talk() throws IOException {
socketChannel.register(selector,
SelectionKey.OP_READ |
SelectionKey.OP_WRITE);
while (selector.select() > 0) {
Set readyKeys = selector.selectedKeys();
Iterator it = readyKeys.iterator();
while (it.hasNext()) {
SelectionKey key = null;
try {
key = (SelectionKey) it.next();
it.remove(); if (key.isReadable()) {
receive(key);
}
if (key.isWritable()) {
send(key);
} }
catch (IOException e) {
// e.printStackTrace();
System.out.println("服务端已关闭");
try {
if (key != null) {
key.cancel();
key.channel().close();
}
}
catch (Exception ex) {
e.printStackTrace();
}
-------------------服务端端开,重新连,也存在二次连接的问题----------
//重新连
reConnect(false);
-----------------------------------------------------------------
}
try {
Thread.sleep(1);
}
catch (InterruptedException ex1) {
}
} //#while
try {
Thread.sleep(5);
}
catch (InterruptedException ex2) {
}
} //#while
}
public void send(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
synchronized (sendBuffer) {
sendBuffer.flip(); //把极限设为位置
socketChannel.write(sendBuffer);
sendBuffer.compact();
}
} public void receive(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
socketChannel.read(receiveBuffer);
receiveBuffer.flip();
String receiveData = decode(receiveBuffer); if (receiveData.indexOf("\n") == -1) {
return;
}
// System.out.println(receiveData);
String outputData = receiveData.substring(0, receiveData.lastIndexOf("\n") + 1);
System.out.print(outputData);
if (outputData.equals("bye\r\n")) {
key.cancel();
socketChannel.close();
System.out.println("关闭与服务器的连接");
selector.close();
System.exit(0);
} ByteBuffer temp = encode(outputData);
receiveBuffer.position(temp.limit());
receiveBuffer.compact();
} public String decode(ByteBuffer buffer) { //解码
CharBuffer charBuffer = charset.decode(buffer);
return charBuffer.toString();
} public ByteBuffer encode(String str) { //编码
return charset.encode(str);
}
private java.util.Timer timer = new java.util.Timer();
}
请帮帮我
网上一些例子写的都是长连接,客户端都是连接了一次,如果在连接期间,服务端关闭,怎么样让客户端定时每隔几秒连一次,直到服务端再打开?
我参考的客户端代码如下
import java.net.*;
import java.nio.channels.*;
import java.nio.*;
import java.io.*;
import java.nio.charset.*;
import java.util.*;public class SocketClient {
private static SocketChannel socketChannel = null;
private int serverPort = 10000;
private ByteBuffer sendBuffer = ByteBuffer.allocate(1024);
private ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);
private Charset charset = Charset.forName("UTF-8");
private Selector selector;
private static boolean flag; public SocketClient() throws IOException {
socketChannel = SocketChannel.open();
InetAddress ia = InetAddress.getLocalHost();
InetSocketAddress isa = new InetSocketAddress(ia, serverPort);
try {
flag = socketChannel.connect(isa);
socketChannel.configureBlocking(false);
System.out.println("与服务器的连接建立成功");
selector = Selector.open();
} catch (SocketException ex) {
System.out.println("connect error");
return;
}
}
public static void main(String args[]) throws IOException {
final SocketClient client = new SocketClient();
flag = socketChannel.isConnected();
if(flag){
Thread receiver = new Thread() {
public void run() {
client.receiveFromUser();
}
}; receiver.start();
client.talk();
}else{
//重新连
--------------此段很模糊 自己乱加的--------
Thread receiver2 = new Thread() {
public void run() {
try {
client.reConnect(flag);
} catch (IOException ex) {
}
}
};
receiver2.start();
---------------------------------------
}
}
//重新连接
public static void reConnect(boolean flag) throws IOException {
while(!flag){
// timer.schedule(new TimerTask() {
// public void run() {
// start();
// timer.cancel();
// }
// public void start() {
// try {
new SocketClient();
// } catch (IOException ex) {
// }
// }
// }, 6000, 6000);
flag = socketChannel.isConnected();
}
------------连是连上了,可是得建立talk,还得用线程,可是线程里的对象一定是final的,所以等于连了两次----
if (flag) {
final SocketClient client2 = new SocketClient();
Thread receiver = new Thread() {
public void run() {
client2.receiveFromUser();
}
};
receiver.start();
client2.talk();
}
------------------------------------------------
} public void receiveFromUser() {
try {
BufferedReader localReader = new BufferedReader(new InputStreamReader(
System.in));
String msg = null;
while ( (msg = localReader.readLine()) != null) {
if ( msg.length() < 1) {
System.out.println("null");
msg = "syn";
} synchronized (sendBuffer) {
sendBuffer.put(encode(msg + "\r\n"));
} if (msg.equals("echo:bye")) {
System.out.println("关闭");
break;
}
if (msg.equals("bye")) {
System.out.println("关闭");
break;
}
}
}
catch (IOException e) {
e.printStackTrace();
}
} public void talk() throws IOException {
socketChannel.register(selector,
SelectionKey.OP_READ |
SelectionKey.OP_WRITE);
while (selector.select() > 0) {
Set readyKeys = selector.selectedKeys();
Iterator it = readyKeys.iterator();
while (it.hasNext()) {
SelectionKey key = null;
try {
key = (SelectionKey) it.next();
it.remove(); if (key.isReadable()) {
receive(key);
}
if (key.isWritable()) {
send(key);
} }
catch (IOException e) {
// e.printStackTrace();
System.out.println("服务端已关闭");
try {
if (key != null) {
key.cancel();
key.channel().close();
}
}
catch (Exception ex) {
e.printStackTrace();
}
-------------------服务端端开,重新连,也存在二次连接的问题----------
//重新连
reConnect(false);
-----------------------------------------------------------------
}
try {
Thread.sleep(1);
}
catch (InterruptedException ex1) {
}
} //#while
try {
Thread.sleep(5);
}
catch (InterruptedException ex2) {
}
} //#while
}
public void send(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
synchronized (sendBuffer) {
sendBuffer.flip(); //把极限设为位置
socketChannel.write(sendBuffer);
sendBuffer.compact();
}
} public void receive(SelectionKey key) throws IOException {
SocketChannel socketChannel = (SocketChannel) key.channel();
socketChannel.read(receiveBuffer);
receiveBuffer.flip();
String receiveData = decode(receiveBuffer); if (receiveData.indexOf("\n") == -1) {
return;
}
// System.out.println(receiveData);
String outputData = receiveData.substring(0, receiveData.lastIndexOf("\n") + 1);
System.out.print(outputData);
if (outputData.equals("bye\r\n")) {
key.cancel();
socketChannel.close();
System.out.println("关闭与服务器的连接");
selector.close();
System.exit(0);
} ByteBuffer temp = encode(outputData);
receiveBuffer.position(temp.limit());
receiveBuffer.compact();
} public String decode(ByteBuffer buffer) { //解码
CharBuffer charBuffer = charset.decode(buffer);
return charBuffer.toString();
} public ByteBuffer encode(String str) { //编码
return charset.encode(str);
}
private java.util.Timer timer = new java.util.Timer();
}
请帮帮我
解决方案 »
- RSA 公钥解密时候报错 BadPaddingException异常,麻烦大家看看
- swing JTree的树节点拖拽问题(急啊!求助!)
- rmi服务端注销掉一个远程对象,客户端为什么还能访问这个远程对象的方法呢?
- java 中 ++ 操作是原子的吗
- 无法将 java.awt.Graphics 中的 getColor() 应用于 (java.awt.Color)
- 各位大虾来帮忙啊!麻烦了
- 怎样注册和使用自定义的新文件类型?
- 我用了MediaTracker 后 , 为什么 paint方法被不停的调用?
- java 中有一条特性
- setbords(int x , int y, int w , int h)?简单,送分!
- 关于 Spring 的问题
- string查找符号字符? 就是查找内容用unicode表示?
你new SocketClient();
两次也就重连了2次
try{
// 连接服务器
// 其它的代码
}catch(Exception ex){
// 如果发生异常,则休眠一段时间
try{
Thread.sleep(1000);
}catch(Exception ee){}
}
}