日期:2014-05-20 浏览次数:20888 次
public class Client { private final Socket receiver; private final Socket sender; public Client() { receiver = ...; sender = ...; } public void receive() { while (true) { 接收... send(msg); } } public void send(String msg) { ... } }
------解决方案--------------------
写了个简单的例子,你试看看能用不,
只是简单的把客户端控制台输出发送在服务器,
服务器把内容打印出来,返回一个字符串给客户端,
并且每5秒钟向所有客户端广播一次系统时间
"java" import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Timer; import java.util.TimerTask; public class TServerSocket { public static void main(String[] args){ final List<SocketProcessor> socketList = new ArrayList<SocketProcessor>(); try { ServerSocket serverSocket = new ServerSocket(12345); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { System.out.println("broadcast"); for(SocketProcessor processor : socketList) processor.writeToString(Calendar.getInstance().getTime().toGMTString()); } }, 100, 5000); while(true){ Socket socket = serverSocket.accept(); SocketProcessor processor = new SocketProcessor(socket); new Thread(processor).start(); socketList.add(processor); } } catch (IOException e) { e.printStackTrace(); } } } class SocketProcessor implements Runnable{ private Socket socket; private InputStream in = null; private OutputStream out = null; public SocketProcessor(Socket socket){ this.socket = socket; try { in = socket.getInputStream(); out = socket.getOutputStream(); } catch (IOException e) { e.printStackTrace(); } } public void writeToString(String info){ try { out.write(info.getBytes()); out.flush(); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { byte[] data = new byte[1024]; while(true){ try { int length = in.read(data); System.out.println(new String(data, 0, length)); out.write("recived".getBytes()); out.flush(); } catch (IOException e) { e.printStackTrace(); } } } }