日期:2014-05-18 浏览次数:20667 次
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();
}
}
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();
}
}