2方法:
第一种使用setSoTimeout方法,超时后重发,你要查查资料,我也不太熟悉,我推荐下一种方法;
第二种有点复杂,首先要设计一个消息对象,包含发送者,接收者,发送时间,内容,发送次数;然后在设计一个消息队列,将消息对象压入队列中;发送的时候可以采用一个线程遍历队列,如果消息的发送时间与当前时间之差小于30秒,同时发送次数小于3,说明消息允许发送,将消息送到socket进行发送,然后pop消息,如果发送不成功,消息发送次数计数,重新入队等待;如果消息的发送时间和次数都不符合规定,直接pop。
第一种使用setSoTimeout方法,超时后重发,你要查查资料,我也不太熟悉,我推荐下一种方法;
第二种有点复杂,首先要设计一个消息对象,包含发送者,接收者,发送时间,内容,发送次数;然后在设计一个消息队列,将消息对象压入队列中;发送的时候可以采用一个线程遍历队列,如果消息的发送时间与当前时间之差小于30秒,同时发送次数小于3,说明消息允许发送,将消息送到socket进行发送,然后pop消息,如果发送不成功,消息发送次数计数,重新入队等待;如果消息的发送时间和次数都不符合规定,直接pop。
do {
Socket socket = null;
try {
socket =
new Socket(InetAddress.getByName("192.168.0.12"), 5005);
socket.setSoTimeout(30000); DataOutputStream output =
new DataOutputStream(socket.getOutputStream());
output.write(message.getBytes()); DataInputStream input =
new DataInputStream(socket.getInputStream());
byte[] m = new byte[20];
input.read(m);
} catch (SocketTimeoutException e) {
System.out.println("err cause==" + e);
try {
if (socket != null) {
socket.close();
}
} catch (IOException ioe) {
System.out.println("error="+ioe);
}
iCount = iCount + 1;
continue;
}
}while(iCount <= 3)
超过三次,跳出这个循环。
再新建一个SOCKET,再发送请求和接收数据,连续三次还是接收不到数据话,跳出这个循环,即不发了。
在同一个SOCKET里重发需要用到另一个线程。
可以把你的程序改成在一个socket内完成吗?
throws IOException, ESMSNotSetException
{
try
{
innerSend(csmsmt);
}
catch(IOException ioexception)
{
try
{
innerSend(csmsmt);
}
catch(IOException ioexception1)
{
innerSend(csmsmt);
}
}
}
import java.net.*;public class chatSvr {
public static void main(String[] str) {
ServerSocket soc;
Socket svrSoc;
DataOutputStream objOut = null;
DataInputStream objIn = null;
try {
System.out.println("Waiting for client's connecting...");
soc = new ServerSocket(5005);
svrSoc = soc.accept();
System.out.println(
"The client connected, you can Exit this program by type 'QUIT'"); objOut = new DataOutputStream(svrSoc.getOutputStream());
objIn = new DataInputStream(svrSoc.getInputStream());
} catch (Exception e) {
System.out.println("error=="+e);
System.exit(0);
} sendMsgOut send = new sendMsgOut(objOut);
send.start();
getMsgFromClient get = new getMsgFromClient(objIn);
get.start();
}
}
class sendMsgOut extends Thread {
DataOutputStream objOut = null;
public sendMsgOut(DataOutputStream out) {
objOut = out;
} public void run() {
String strMsg = "";
while (true) {
try {
//strMsg = (new BufferedReader(new InputStreamReader(System.in))).
// readLine();
strMsg = "kill you";
objOut.write(strMsg.getBytes());
System.out.println("get data!");
if (strMsg.equals("QUIT"))
System.exit(0);
} catch (Exception e) {}
}
}}
class getMsgFromClient extends Thread {
DataInputStream objIn;
boolean rightFlag = false;
String strMsg = "";
public getMsgFromClient(DataInputStream in) {
objIn = in;
} public void run() {
while (true) {
try {
byte[] bb = new byte[1024];
objIn.read(bb);
System.out.println("The client said:" + bb.toString());
if (strMsg.equals("QUIT"))
System.exit(0);
} catch (Exception e) {}
}
}
}