期待ing我现在也要用java写个客户端编译老是通不过啊

解决方案 »

  1.   

    什么“实时测控交流调速系统”我不懂,不过这个Socket编程应该不难吧。如果我没看出来,你告诉我难点在哪里好了。主要就是写服务器端和客户端咯。至于你要求的同步,不知道要求高到什么程度呢?http://java.sun.com/docs/books/tutorial/networking/sockets/clientServer.html看一下这个例子吧。如果同步传输要求高的话,需要用多线程来解决。
      

  2.   

    谢谢,大家up。在这里深表感谢,确实不难,只是在下学时浅薄,才来寻求兄弟们帮忙,
    特别感谢mercury 兄,确实要求不很高的一个编程,只是多线程部分要难些!(当人是对于
    我这样的初学者来说:)如果mercury兄有空,可以留段代码,没有多线程部分也可以
    有注释当然最好了,
    在下 大连 qq 22504826, 帮忙统统给分,谢谢捧场!
      

  3.   

    给你一段在我写的系统里的代码:
    ////////////////////////////////////////////////////////////////////////
    /**
     * <p>Title: 端口监听类PortListener,负责监听端口,这个类需要传进两个参数
     *1.主Frame. 2.ServerSocket:服务端socket</p>
     * <p>Description:</p>
     * <p>Copyright: Copyright (c) 2002</p>
     * <p>Company: </p>
     * @author phf
     * @version 1.0
     */import java.io.*;
    import java.net.ServerSocket;
    import java.net.Socket;public class PortListener implements Runnable{
        /**服务器监听对象*/
        private ServerSocket sSocket;
        /**主窗口*/
        private MainFrame mainFrm;
        /**与客户交互的Socket*/
        private Socket cSocket;
        /**
         * 构造函数
         * @param mainFrm 主窗口
         * @param sSocket 服务器监听对象
         */
        public PortListener(MainFrame mainFrm,ServerSocket sSocket) {
            this.mainFrm=mainFrm;
            this.sSocket=sSocket;
        }    public void run (){
            if (sSocket==null){
                mainFrm.addMessage("监听服务不存在!",false);
                return;
            }
            while(true){
                try {
                    cSocket=sSocket.accept();
                    Thread cs=new Thread(new ClientSession(this.mainFrm,cSocket));
                    cs.start();
                }catch(Exception e){
                    mainFrm.addMessage("启动客户会话进程错误:"+e.getMessage(),false);
                }
            }
        }
    }/////////////////////////////////////////////////////////////////////////
    /**
     * <p>Title:客户会话类ClientSession ,负责与客户机对话,每个客户端对应一个线程</p>
     * <p>Copyright: Copyright (c) 2002</p>
     * <p>Company: </p>
     * @author phf
     * @version 1.0
     */
    import java.io.*;
    import java.net.Socket;
    import com.broadcontact.tools.*;
    import com.broadcontact.emp.ComData;
    import java.util.Date;
    import java.util.Collection;
    import java.util.Iterator;public class ClientSession implements Runnable{
        /**主窗口*/
        private MainFrame mainFrm;
        /**与客户交流的Socket*/
        private Socket cSocket = null;
        /**客户端对应用户的信息*/
        private UserInfo uInfo=new UserInfo();
        /**信息读写*/
        private Messages Msg=null;
        /**系统所有共用数据*/
        private ComData comData=null;
        /**
         * 构造函数
         * @param mainFrm 主窗口
         * @param cSocket 与客户交流的Socket
         */
        public ClientSession (MainFrame mainFrm,Socket cSocket) {
            this.mainFrm=mainFrm;
            this.comData=mainFrm.comData;
            this.cSocket=cSocket;
        }
        /**
         * 初始化输入输出
         * @return
         */
        private boolean init(){
            //用取得的Socket构造输入输出流
            try{
                Msg=new Messages(cSocket.getInputStream(),cSocket.getOutputStream());
            }catch(Exception e){
                mainFrm.addMessage("创建网络输入/输出流错误:"+e.getMessage(),false);
                return false;
            }
            return true;
        }
        /**
         * 运行线程
         */
        public void run () {
           //你的处理代码
        }
        ...................................//////////////////////////////////////////////////////////////////////在你的主进程里先New ServerSocket(端口号),然后New PortListener(用启动线程的方法启动PortListener线程),就可以了。
      

  4.   

    不难看出,phf兄,是很有生活水准和专业精神的热心人,在下感谢佩服,我甘当“旺财”,
    我会好好学习你的代码,不懂的地方还希望赐教 。
    谢了,点数不会少给热心哥们的!
      

  5.   

    非常感谢,  
    其实说具体点我实现的是对交流调速电机电压,电流变化的实时检测,
    客户界面和主机接受的交流调速电机的数据都有了,就缺java,socket实现的
    主机 客户交换数据,隔一段时间检测 电压 电流等 有没有变化,有变化客户端跟着改,
    划曲线,然后取个值 (这部分已经做好了),把取得值送回给服务器,就是这个过程,
    最好同时监测变化取服务器数据,和客户送数据给服务器,是不冲突,所以用多线程,
    如果多线程 麻烦,不用也行!!!
    您列出的功能类似于我说的功能,对我要实现的也大有帮助,我研究一下!
      

  6.   

    我给你一个我做的服务器的多线程的程序,功能是负责客户端的转发,希望对你有用。这个程序使用了JAVA非标准库,加密包,因为如果加上那些代码实在太长所以我就没有给了,主要是的线程处理就在程序最前面.开发环境是JDK.1.4
    public class jms
    {
    static String [] guestname = new String[10];
    static String [] miyao = new String[10];
    static Socket[] pans = new Socket[10];
        static PrintWriter[] ppout =new PrintWriter[10];
        static BufferedReader[] ppin = new BufferedReader[10];
    static int laiyuan=0;
    static int woziji=0;
        public static void main(String[] args) throws IOException
        {
            //声明一个serverSocket
    ServerSocket serverSocket = null;
            //线程编号
            int i=1;
       //声明一个监听标识

    //static String [] guestname = new String[10];
    guestname[1]="guest1pan";
    guestname[2]="guest2zhao";
    guestname[3]="guest3wang";
    guestname[4]="guest4zhang";
    guestname[5]="guest5chen";
    guestname[6]="guest6zhou";
    guestname[7]="guest7guo";
    guestname[8]="guest8cai";
    guestname[9]="guest9fang";
    //String [] miyao = new String[10];
    miyao[1]="11111111";
    miyao[2]="22222222";
    miyao[3]="33333333";
    miyao[4]="44444444";
    miyao[5]="55555555";
    miyao[6]="66666666";
    miyao[7]="77777777";
    miyao[8]="88888888";
    miyao[9]="99999999";
    String zhuchestring=null;
    boolean [] zaixian = new boolean[10];
    int zhuchehao=0;
    zaixian[1]=false;
    zaixian[2]=false;
    zaixian[3]=false;
    zaixian[4]=false;
    zaixian[5]=false;
    zaixian[6]=false;
    zaixian[7]=false;
    zaixian[8]=false;
    zaixian[9]=false;
            boolean listening = true;
            try
            {
                serverSocket = new ServerSocket(8998);        }
            catch (IOException e)
            {
                System.err.println("Could not listen on port: 8998.");
                System.exit(1);
            }
    //处于监听态,当客户连接则开启一个线程处理
            while(listening)
            {
                //客户连接,启动编号为i的一个线程
                Socket incoming = serverSocket.accept( );
    PrintWriter tempout = new PrintWriter(incoming.getOutputStream(), true);
    BufferedReader tempin = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
    System.out.println("客户:" + i);

    if(tempin.readLine().compareTo("load")==0)
      {
                  zhuchestring=tempin.readLine();
      zhuchehao=Integer.parseInt(zhuchestring);
      
      pans[zhuchehao]=incoming;
                  ppout[zhuchehao] = new PrintWriter(incoming.getOutputStream(), true);
                  ppin[zhuchehao] = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
      
      zaixian[zhuchehao]=true;
      ppout[zhuchehao].println(guestname[zhuchehao]+"  您的注册号是"+zhuchehao+"**");
      System.out.println("load");
      }
      ////////////////显示在线的客户
      for(int ii=1;ii<zhuchehao;ii++)//客户数
    if(zaixian[ii])
       ppout[ii].println(String.valueOf(zhuchehao)+"注册号:"+zhuchehao+"  用户名:  "+guestname[zhuchehao]+"~~~");
      
      for(int ii=zhuchehao+1;ii<10;ii++)//客户数
    if(zaixian[ii])
       ppout[ii].println(String.valueOf(zhuchehao)+"注册号:"+zhuchehao+"  用户名:  "+guestname[zhuchehao]+"~~~");
      
      for(int jj=1;jj<10;jj++)
      if(zaixian[jj])
         ppout[zhuchehao].println(String.valueOf(jj)+"注册号:"+jj+"  用户名:  "+guestname[jj]+"~~~");
      new EchoMultiServerThread(incoming, i).start();
                  i++;
            }
            //将serverSocket的关闭操作放在循环外,
            //只有当监听为false是,服务才关闭
            serverSocket.close();
            }
    }
      

  7.   

    //通信线程类:
    class EchoMultiServerThread extends Thread {
        private Socket incoming = null;//通信套接字
        private int counter=0;         //客户编号
        //构造函数:
        public EchoMultiServerThread(Socket s,int i) {
             incoming = s; 
             counter = i;
        }
        //重载线程体,处理客户-服务器通信
        public void run() {
            try
    {
         String myks = "12345678";
     DesCipher my = new DesCipher(myks);
     String mych;
     byte[] k = new byte[8];
             byte[] p = new byte[8];
     byte[] h = new byte[8];
     byte[] rankey = new byte[8];
     byte[] zijimikey = new byte[8];
     byte[] mudimikey = new byte[8];
     String zhongjianstring=null;
             //my.setKey("ampanpan");
    //建立输出、输入流
                PrintWriter out = null;
            BufferedReader in = null;
                out = new PrintWriter(incoming.getOutputStream(), true);
                in = new BufferedReader(new InputStreamReader(incoming.getInputStream()));
                int ziji=0;
    int mudi=0;
    //int laiyuan=0;
    //int woziji=0;
                while(true)
                {
              String str = in.readLine();
                if(str.compareTo("quliaotianmiyao")==0)
    {
        int liaotianziji=Integer.parseInt(in.readLine());
                    int liaotianduifang=Integer.parseInt(in.readLine());
        byte[] liaokey = new byte[8];
    byte[] tempkey = new byte[8];
    Random liao=new Random();
                    liao.nextBytes(liaokey);
    for(int iii=0;iii<8;iii++)
    System.out.println("明"+liaokey[iii]);//明
    out.println("keyijiamichuanliaotianle");
    my.setKey(jms.miyao[liaotianziji]);
    my.encrypt(liaokey,0,tempkey,0);
    for(int iii=0;iii<8;iii++)
    {
        out.println(tempkey[iii]);
        System.out.println(tempkey[iii]);
    }
    my.setKey(jms.miyao[liaotianduifang]);
            my.encrypt(liaokey,0,tempkey,0);
    for(int iii=0;iii<8;iii++)
    {
        out.println(tempkey[iii]);
    System.out.println(tempkey[iii]);
    }
    continue;
        }
    else if(str.compareTo("liaotian")==0)
    {
        //System.out.println(in.readLine());
        int liaotianduifang=Integer.parseInt(in.readLine());
                    System.out.println(liaotianduifang);
    jms.ppout[liaotianduifang].println("liaotianmudi");
    for(int iii=0;iii<8;iii++)
    jms.ppout[liaotianduifang].println(in.readLine());
    jms.ppout[liaotianduifang].println(in.readLine());
    for(int iii=0;iii<8;iii++)
      jms.ppout[liaotianduifang].println(in.readLine());

    continue;
    }

    else if(str.compareTo("send")==0)
    {
         System.out.println("send sucess!");
     ziji=Integer.parseInt(in.readLine());
     System.out.println(jms.guestname[ziji]);
     System.out.println(jms.miyao[ziji]);
         mudi=Integer.parseInt(in.readLine());  
     System.out.println(jms.guestname[mudi]);
     System.out.println(jms.miyao[mudi]);
                    
     Random kkk=new Random();
     kkk.nextBytes(rankey);
     for(int iii=0;iii<8;iii++)
       System.out.println(rankey[iii]);
                     
     my.setKey(jms.miyao[ziji]);
     my.encrypt(rankey,0,zijimikey,0); 
     for(int iii=0;iii<8;iii++)
       System.out.println(zijimikey[iii]);
     
     my.setKey(jms.miyao[mudi]);
     my.encrypt(rankey,0,mudimikey,0);
     for(int iii=0;iii<8;iii++)
       System.out.println(mudimikey[iii]);
                     //////////////////////////
     out.println("mimi");
     for(int iii=0;iii<8;iii++)
       out.println(zijimikey[iii]);
             for(int iii=0;iii<8;iii++)
       out.println(mudimikey[iii]);
     continue;
        }
    else if(str.compareTo("sendmimifile")==0)
    {
    jms.ppout[mudi].println("sendmimifile");

    //jms.ppout[mudi].println(ziji);//转fa
    //jms.ppout[mudi].println(mudi);//转fa

    jms.laiyuan=Integer.parseInt(in.readLine());
    jms.woziji =Integer.parseInt(in.readLine());
    System.out.println(jms.laiyuan);
    System.out.println(jms.woziji);
    //while((zhongjianstring=in.readLine()).compareTo("sendmimifileover")==0)
    //jms.ppout[mudi].println(zhongjianstring);
    continue;
    }
    else if(str.compareTo("dedao")==0)
    {
    //ziji=Integer.parseInt(in.readLine());
    //mudi=Integer.parseInt(in.readLine());
    System.out.println(jms.woziji);
    jms.ppout[jms.woziji].println("dedao");//mudi...................
    str=in.readLine();
    while(str!="over")
    {
        jms.ppout[jms.woziji].println(str);//mudi
        str=in.readLine();
        }
    str=null;
    continue;
    }
    if(str.compareTo("bye")==0)
    break;
    else if(str.compareTo("get")==0)
    {
      System.out.println("ok,转发了GET");
      //int laiyuan=Integer.parseInt(in.readLine());
      //woziji=Integer.parseInt(in.readLine());
      System.out.println(jms.laiyuan);
      //System.out.println(woziji);
      //ziji=Integer.parseInt(in.readLine());
      //mudi=Integer.parseInt(in.readLine());
      jms.ppout[jms.laiyuan].println("ok");//ziji...................
          //jms.ppout[ziji].println("ok");
      System.out.println("ok,转发了GET9999");
      //???????????????????
      //FileInputStream fin = new FileInputStream("mimi.txt");
          //boolean m_f=true;
      //while(m_f)
    //{
      
                      //if(8!=fin.read(k,0,8))
                         //m_f=false;
                      
      //my.encrypt(k,0, p,0);//加密
      //for(int i=0;i<8;i++)
    //{   
        //System.out.println(k[i]);
                        //out.println(String.valueOf(p[i]));
    //}    //for(int i=0;i<8;i++)
    //{
       // p[i]=0;
    //k[i]=0;
        // }
    //}
     // fin.close();
                        continue;
    }
                }
                
                out.close();
            in.close();
            incoming.close();
    } catch (IOException e) 
    {  e.printStackTrace(); }
    }
    }
      

  8.   

    onetime(火舞耀阳) :
    我想了解你的监控服务器端同时监控几个客户端,如只有一个的话,你的socket通讯用单线程应该没什么问题,如果是同时监控多个客户端,那必须要用多线程来接收客户端的请求。
      

  9.   

    MyServer.java
    import java.net.*;
    import java.io.*;
    import java.lang.*;public class MyServer extends Thread
    {
    private int port;
    private final static int DEFAULT_SERVER_PORT=1234;
    private ServerSocket srvSock; public static void main(String args[])
    {
             int port=1234;
     if(args.length==1)
     {
     try
         {
                   port=Integer.parseInt(args[0]);
     }
     catch(NumberFormatException e)
         {
                   System.out.println("Expecting a numeric argument!");
         }
         new MyServer(port);
     }
     else
     {
                 new MyServer();
         }
    } public MyServer(int port)
        {
             this.port=port;
     try
     {
                srvSock=new ServerSocket(port);
     }
             catch(BindException e)
     {
                System.out.println("BindException:"+e);
    System.exit(1);
     }
     catch(SocketException e)
     {
                System.out.println("SocketException:"+e);
    System.exit(1);
             }
     catch(IOException e)
     {
                System.out.println("IOException"+e);
    System.exit(1);
             }
     System.out.println("MyServer:Listening on port "+port);
     start();
    } public MyServer()
    {
          this(DEFAULT_SERVER_PORT);
        } public void run()
    {
          Socket clientSock=null;
      while(true)
    {
              try
      {
                clientSock=srvSock.accept();
    System.out.println("ms_run_1");
      }
      catch(IOException e)
      {
                 System.out.println("IOException on accept");
         System.exit(1);
      }
      ServerLogic srvLogic=new ServerLogic(clientSock);
      srvLogic=null;
    }
    }
    }
    class ServerLogic extends Thread
    {    protected Socket clientSock;
    protected InputStream is;
    protected DataInputStream dis;
    protected OutputStream os;
    protected PrintStream pos;
        
    public ServerLogic(Socket clientSock)
    {
           this.clientSock=clientSock;
       System.out.println("sl_sl_1");
       try
    {
               is=clientSock.getInputStream();
       dis=new DataInputStream(is);
       os=clientSock.getOutputStream();
       pos=new PrintStream(os);
           System.out.println("sl_sl_2");
    }
       catch(IOException e)
    {
               System.out.println("IOException on getting streams for socket");
       try
    {
                  clientSock.close();
    }
       catch(IOException ie)
    {
                  System.out.println("IOException on closing socket");
    }
    }
       start();
    } public void run()
        {
            String clientMsg;
        System.out.println("sl_run_1");
    try
    {
              clientMsg=dis.readLine();
      System.out.println(clientMsg);
    }
    catch(IOException e)
        {
              System.out.println("IOException reading line:\n"+e);
          return;
    }
    int msgLen=clientMsg.length();
    pos.println("Client message had "+msgLen+" characters.");
    System.out.println("Client message had "+msgLen+" characters.");
        }
    }
    ______________________________________________
    MyClient.java
    import java.net.*;
    import java.io.*;
    import java.lang.*;public class MyClient extends Object
    {
    private int port;
    private final static int DEFAULT_PORT=1234;
    private ServerSocket srvSock;
    private static String promptStr="#"; public static void main(String args[])
    {
           int port=1234;
       if(args.length!=1 && args.length!=2)
    {
                printUsage();
    System.exit(0);
    }
    else if(args.length==1)
    {
                port=DEFAULT_PORT;
    }
    else
    {
                try
    {
    port=Integer.parseInt(args[1]);
    }
    catch(NumberFormatException e)
    {
                    System.out.println("Must use a number for the port value!");
    printUsage();
    System.exit(1);
    }
    }
            client(args[0],port);  
    } private static void printUsage()
    {
    System.out.println("Usage: java MyClient host [port]");
    } private static void client(String host,int port)
    {
    Socket clientSock=null;
    try
    {
    clientSock=new Socket(host,port);
    }
    catch(UnknownHostException e)
    {
                 System.out.println(e);
     System.exit(1);
    }
    catch(ConnectException e)
    {
                 System.out.println(e);
     System.exit(1);
    }
    catch(NoRouteToHostException e)
    {
                 System.out.println(e);
     System.exit(1);
    }
    catch(IOException e)
    {
                 System.out.println(e);
     System.exit(1);
    }
    System.out.println("Connect to the host"+host+"("+clientSock.getInetAddress()+")"+" at port "+clientSock.getPort()); InputStream is=null;
            OutputStream os=null;
    DataInputStream dis;
    PrintStream ps;
    try
    {
               is=clientSock.getInputStream();
    }
    catch(IOException e)
    {
    System.out.println("IOException on getting input stream");
    }
    try
    {
    os=clientSock.getOutputStream();
    }
    catch(IOException e)
    {
    System.out.println("IOException on getting output stream");
    }
    dis=new DataInputStream(is);
    ps=new PrintStream(os);
    DataInputStream cis=new DataInputStream(System.in);
    String buff;
    while(true)
    {
              System.out.print(promptStr);
      System.out.flush();
      try
      {
              System.out.println("\n1");
      buff=cis.readLine();
      }
      catch(IOException e)
      {
      System.out.println("IOException reading form console");
      break;
      }
      if(buff==null)
    {
        System.out.println("Buff is null_1");
    break;
    }
      ps.println(buff);   try
    {
                System.out.println("\n2");
    buff=dis.readLine();  //无返回
    }
      catch(IOException e)
    {
      System.out.println("IOException reading from socket");
      break;
    }
      if(buff==null)
    {
      System.out.println("Buff is null_2");
      break;
    }
      System.out.println(buff);
    }
    }
    }
      

  10.   

    建立连接之后就简单了,如果你想方便可以用ObjectInputStream和ObjectOutputStream读写对象(对象必须实现Serializable接口)。
    例如:
    public class MsgObject implements Serializable {
        /**短信id*/
        private int id=0;
        /**发送人地址*/
        private String src_addr="";
        get和set方法.........
        
    }然后实现读:
    ObjectInputStream ois=new ObjectInputStream(Socket.getInputStream());
    就可以实现了。
    MsgObject mobj=(MsgObject)ois.readObject();实现写就差不多,看看JDK API Doc就可以了