java 生成数据报表代码

2014-11-23 23:38:06 · 作者: · 浏览: 0
执行时,服务端使用java test 1启动,客户端使用java test启动,当服务器端键入字符时,客户端也会打印出相应的字符,希望下面的代码对你有所收获。

  1. import java.net.*;
  2. public class test {
  3. public static int serverPort = 666;
  4. public static int clientPort = 999;
  5. public static int buffer_size = 1024;
  6. public static DatagramSocket ds;
  7. public static byte buffer[]=new byte[buffer_size];
  8. public static void TheServer() throws Exception {
  9. int pos=0;
  10. while(true){
  11. int c = System.in.read();
  12. switch(c){
  13. case :
  14. ds.send(new DatagramPacket(buffer,pos,InetAddress.getLocalHost(),clientPort));
  15. pos = 0;
  16. break;
  17. default :
  18. buffer[pos ]=(byte)c;
  19. }
  20. }
  21. }
  22. public static void TheClient() throws Exception{
  23. while(true){
  24. DatagramPacket p = new DatagramPacket(buffer,buffer.length);
  25. ds.receive(p);
  26. System.out.println(new String(p.getData(),0,p.getLength()));
  27. }
  28. }
  29. public static void main(String[] args) throws Exception{
  30. // TODO Auto-generated method stub
  31. if(args.length==1){
  32. ds = new DatagramSocket(serverPort);
  33. TheServer();
  34. }else{
  35. ds = new DatagramSocket(clientPort);
  36. TheClient();
  37. }
  38. }
  39. }