客户端code
public class Client implements Runnable{
private static Socket s;
private Socket getInstance(){
if(s==null){
try {
return s=new Socket("127.0.0.1",8000);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return s;
}
public void sendMsg() {
while(true){
try {
run();
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
@Override
public void run() {
System.out.println("come into run");
try {
Socket c = getInstance();
OutputStream ops =c.getOutputStream();
ops.write(new byte[]{0000});
ops.flush();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException ex) {
// TODO Auto-generated catch block
ex.printStackTrace();
}
}
public static void main(String[] args) {
Client c = new Client();
c.sendMsg();
}
}
服务端code
public class Server {
private ServerSocket serverSocket;
public Server(){
try {
serverSocket = new ServerSocket();
serverSocket.bind(new InetSocketAddress(8000));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("服务启动");
}
public void service() {
while (true) {
Socket s = null;
try {
s = serverSocket.accept();
System.out.println("come a new request~ "+s.getInetAddress()+":"+s.getPort());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if(s!=null)
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Server server = new Server();
server.service();
}
}
我的想法是每隔3秒往服务端发送一个数据包,现在的情况是会抛异常:
java.net.SocketException: Software caused connection abort: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
at com.ls.test.Client.run(Client.java:44)
at com.ls.test.Client.sendMsg(Client.java:28)
at com.ls.test.Client.main(Client.java:57)
我发现可能是server端把socket close的原因所以去掉了关闭代码:
finally {
if(s!=null)
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
但现在服务端确只接受一次请求了,不知道为什么
socket java
------解决方案--------------------
serverSocket.accept();//这一行会被阻塞
看一下accept的介绍,注意红色部分:
Listens for a connection to be made to this socket and accepts it. The method blocks until a connection is made.
它说这个方法在新的连接到来之前会一直被阻塞。
而在客户端你写的方法:
private Socket getInstance(){}
这个方法保证了只会建立一次连接。
也就是说客户端在第一次连接建立之后没有新的连接了,而服务端的死循环里接收到第一次连接并打印之后马上又去傻傻的等待第二次连接了,它肯定是等不到的,So……