java server怎样和c++ client实现SSL通信??

java keytool生成的证书是CRT等格式的,这种格式是2进制编码的,而C++用的证书格式是pem,pem是ascii编码的。
我用keytool无法生成pem,并且又无法把C CLIENT给我的pem放进我的truststore中。
weblogic还只能用JKS来实现SSL 
求高端玩家帮忙呀。。。


问题补充:beneo 写道socket跟语言无关
没错 但是产品和语言有关  有个中转服务器用的oracle service bus 。只支持JKS格式 也就是java的KEYTOOL生成的key库。所以才有了我现在问的这个问题

问题补充:beneo 写道引用
java keytool生成的证书是CRT等格式的,这种格式是2进制编码的,而C++用的证书格式是pem,pem是ascii编码的。

有个中转服务器用的oracle service bus 。只支持JKS格式 也就是java的KEYTOOL生成的key库。所以才有了我现在问的这个问题


那是否就是说,我只需要能够把c client产生的证书用Reader读一下,然后在用outputStream写一下,就能生成2进制的文件呢?如果不行的话,注意下big endian 和 little endian,这个是C++和java互通经常存在的问题



不是用Stream读的 是配置路径OSB自己读的。现在找到了一些办法 还没试成功。因为keytool用的CA server和C的CA server不一样,所以用了OPENSSL的CA给他们统一签名,并且OPENSSL可以让DER,PEM互相转换。思路现在大致有的,也做了,但是还没成功哈。

回答: java server怎样和c++ client实现SSL通信??

  1. 引用
    java keytool生成的证书是CRT等格式的,这种格式是2进制编码的,而C++用的证书格式是pem,pem是ascii编码的。

    有个中转服务器用的oracle service bus 。只支持JKS格式 也就是java的KEYTOOL生成的key库。所以才有了我现在问的这个问题


    那是否就是说,我只需要能够把c client产生的证书用Reader读一下,然后在用outputStream写一下,就能生成2进制的文件呢?如果不行的话,注意下big endian 和 little endian,这个是C++和java互通经常存在的问题


想写一个程序,server端在家里,client端在公司,通过互联网进行连接

  1. Q
    想写一个程序,server端在家里,client端在公司,通过互联网进行连接,能够实现连接建立以及传输数据就行了

    想在Linux下用c实现,麻烦知道的提示一下,使用什么协议,需要哪些条件,要注意什么,大概有点像使用手机远程控制智能家居的那种通信方式,如果有源码,不甚感谢。
  2. A
    可以为自己家里的Server申请一个DDNS,通过域名访问。然后只要在公司能访问这个域名就可以进行通信了!

    动态域名是一个思路 花生壳可以用吧

java中的httpclient的SSL出错

  1. Q
    我直接下载最新版的httpclient,直接复制的示例中的代码,只是把网址换成我自己想要的网址.并且,在我电脑中,在办公室服务器里测试都通过,但上传上机房服务器里面就出错了.

    java代码
    	public void login()
    	{
            try
            {
            	//初始化 httpclient
            	DefaultHttpClient httpclient = new DefaultHttpClient();
            	//设置证书
    	        httpclient.getConnectionManager().getSchemeRegistry().register(sch);
    	        String url = "login.jsp";
    	        HttpPost httpost = new HttpPost(url);
    	        print("准备登陆网站,网址:"+url);
    	        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
    	        nvps.add(new BasicNameValuePair("actionName", "login"));
    	        nvps.add(new BasicNameValuePair("login_password", "11"));
    	        nvps.add(new BasicNameValuePair("login_user", "111"));	      
    	        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    	        HttpResponse response = httpclient.execute(httpost);
    	        String statusLine = response.getStatusLine().toString();
    	        print("得到网页打开状态"+statusLine);
    	        if(statusLine.equals("HTTP/1.1 200 OK"))
    	        {
                     }  
                 }
             }
    	/*
    	 * 设置SSL证书
    	 */
    	public void setSSL()
    	{
            try
            {
    			KeyStore trustStore  = KeyStore.getInstance(KeyStore.getDefaultType());      
    			String p = System.getProperty("user.dir")+"/my.key";
    			print(p);
    	        FileInputStream instream = new FileInputStream(new File(p)); 
    	        try {
    	        	trustStore.load(instream, "123456".toCharArray());
    	        }catch(Exception e)
    	        {
    	        	e.printStackTrace();
    	        }
    	        finally {
    	            instream.close();
    	        }     	             
    	    	SSLSocketFactory socketFactory = new SSLSocketFactory(trustStore);
    	        sch = new Scheme("https", socketFactory, 443);
            }
            catch(Exception e)
            {
            	e.printStackTrace();
            }
    	}
    


    程序出错提示
    javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
            at sun.security.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:371)
            at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:128)
            at org.apache.http.conn.ssl.SSLSocketFactory.createSocket(SSLSocketFactory.java:399)
            at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:143)
            at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:149)
            at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:108)
            at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:415)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:641)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:576)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:554)
            at login(login.java:89)
    
  2. A
    referenced this link
    http://theskeleton.wordpress.com/2010/07/24/avoiding-the-javax-net-ssl-sslpeerunverifiedexception-peer-not-authenticated-with-httpclient/

    The following class takes a HttpClient and returns a new HttpClient that accepts any SSL certificate:
    01 public class WebClientDevWrapper {
    02
    03     public static HttpClient wrapClient(HttpClient base) {
    04         try {
    05             SSLContext ctx = SSLContext.getInstance("TLS");
    06             X509TrustManager tm = new X509TrustManager() {
    07
    08                 public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
    09                 }
    10
    11                 public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
    12                 }
    13
    14                 public X509Certificate[] getAcceptedIssuers() {
    15                     return null;
    16                 }
    17             };
    18             ctx.init(null, new TrustManager[]{tm}, null);
    19             SSLSocketFactory ssf = new SSLSocketFactory(ctx);
    20             ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    21             ClientConnectionManager ccm = base.getConnectionManager();
    22             SchemeRegistry sr = ccm.getSchemeRegistry();
    23             sr.register(new Scheme("https", ssf, 443));
    24             return new DefaultHttpClient(ccm, base.getParams());
    25         } catch (Exception ex) {
    26             ex.printStackTrace();
    27             return null;
    28         }
    29     }
    30 }

    You can then do something like this in the code that creates the HttpClient:
    1 this.client = new DefaultHttpClient();
    2 if(dev) {
    3     this.client = WebClientDevWrapper.wrapClient(client);
    4 }


    referenced this link
    http://theskeleton.wordpress.com/2010/07/24/avoiding-the-javax-net-ssl-sslpeerunverifiedexception-peer-not-authenticated-with-httpclient/

一个关于java数据报做的简单聊天的问题

  1. Q
    数据只能从Client端发送到Server端,Server端发送到Client端不仅重复发送,而且Client端貌似接收不到,请问问题出在哪里,怎么解决? PS:希望能在Client端之间聊天 :) [code="java"] public class Server extends JFrame implements Runnable { final static int MEMBER_COUNT = 2,PORT_NUMBER =5000;//最大连接数目 private JTextArea displayArea; // displays packets received private DatagramSocket socket; // socket to connect to client Member[] members; int number = 0;//已经连接到的client数目 // 创建 GUI 和 DatagramSocket public Server() { super( "Server" ); members =new Member[Server.MEMBER_COUNT]; displayArea = new JTextArea(); // create displayArea add( new JScrollPane( displayArea ), BorderLayout.CENTER ); setSize( 400, 300 ); // set size of windows this.addWindowListener(new WindowAdapter(){ @Override public void windowClosing(WindowEvent e) { // TODO Auto-generated method stub socket.close(); } }); setVisible( true ); // show window try // create DatagramSocket for sending and receiving packets { socket = new DatagramSocket( Server.PORT_NUMBER ); } // end try catch ( SocketException socketException ) { socketException.printStackTrace(); System.exit( 1 ); } // end catch } // end Server constructor //连接到服务器 public boolean connectTo(InetAddress address) { for(int i=0;i<server.member_count if members new member number this.displaymessage return true false private boolean isfirst a for i="0;i&lt;Server.MEMBER_COUNT;i++)" public void waitforpackets while try receive packet display contents copy to client byte data set up datagrampacket receivepacket="new" data.length socket.receive wait this.connectto system.out.printf string sendpackettoclient send end catch ioexception displaymessage ioexception.tostring ioexception.printstacktrace method echo throws create sendpacket receivepacket.getlength socket.send manipulates displayarea in the event-dispatch thread final messagetodisplay swingutilities.invokelater runnable run updates displayarea.append message anonymous inner class call todo auto-generated stub server extends jframe implements jtextfield enterfield entering messages jtextarea displaying datagramsocket socket connect name gui and myname super here enterfield.addactionlistener actionlistener actionperformed actionevent event get from textfield message.getbytes convert bytes inetaddress.getlocalhost enterfield.settext addactionlistener add borderlayout.north jscrollpane borderlayout.center setsize window size setvisible show sending receiving packets socketexception socketexception.printstacktrace system.exit constructor arrive system.out.println ok receivepacket.getdata exception exception.tostring exception.printstacktrace int port inetaddress address this.port="port;" this.address="address;" servertest static main args application="new" client1="new" executorservice e="Executors.newFixedThreadPool(3);" e.execute></server.member_count>
    问题补充:代码太乱了- -再发一遍
    public class Server extends JFrame implements Runnable
    {
    final static int MEMBER_COUNT = 2,PORT_NUMBER =5000;//最大连接数目
       private JTextArea displayArea; // displays packets received
       private DatagramSocket socket; // socket to connect to client
       Member[] members;
       int number = 0;//已经连接到的client数目
       // 创建 GUI 和 DatagramSocket
       public Server()
       {
          super( "Server" );
          members =new Member[Server.MEMBER_COUNT];
          displayArea = new JTextArea(); // create displayArea
          add( new JScrollPane( displayArea ), BorderLayout.CENTER );
          setSize( 400, 300 ); // set size of windows
          this.addWindowListener(new WindowAdapter(){

    @Override
    public void windowClosing(WindowEvent e) {
    // TODO Auto-generated method stub
    socket.close();
    }

          });
          setVisible( true ); // show window

          try // create DatagramSocket for sending and receiving packets
          {
             socket = new DatagramSocket( Server.PORT_NUMBER );
          } // end try
          catch ( SocketException socketException )
          {
             socketException.printStackTrace();
             System.exit( 1 );
          } // end catch
       } // end Server constructor
       //连接到服务器
       public boolean connectTo(InetAddress address)
       {
    for(int i=0;i<Server.MEMBER_COUNT;i++)
    {
    if(members[i]==null)
    {
    members[i] = new Member(Server.PORT_NUMBER,address);
    number++;
    this.displayMessage("连接成功");
    return true;//连接成功
    }
    }
    return false;//连接失败
       }
       private boolean isFirst(InetAddress a)//是否存在这个ip
       {
       for(int i=0;i<Server.MEMBER_COUNT;i++)
       {
       if(members[i]!=null&&a.equals(members[i].address)) return false;//已经存在
       }
       return true;//是第一次发送
       }
       // 等待接收并将接收到的包发送
       public void waitForPackets()
       {
          while ( true )
          {
             try // receive packet, display contents, return copy to client
             {
                byte data[] = new byte[ 100 ]; // set up packet
                DatagramPacket receivePacket =
                   new DatagramPacket( data, data.length );

                socket.receive( receivePacket ); // wait to receive packet
         
                if(isFirst(receivePacket.getAddress()))//第一次发送
                this.connectTo(receivePacket.getAddress());//连接
                System.out.printf("send \"%s\" to client\n", new String(receivePacket.getData(),
                0,receivePacket.getLength()));
                sendPacketToClient( receivePacket ); // send packet to client
             } // end try
             catch ( IOException ioException )
             {
                displayMessage( ioException.toString() + "\n" );
                ioException.printStackTrace();
             } // end catch
          } // end while
       } // end method waitForPackets

       // echo packet to client
       private void sendPacketToClient( DatagramPacket receivePacket )
          throws IOException
       {


          // create packet to send
          DatagramPacket sendPacket;
          for(int i=0;i<Server.MEMBER_COUNT;i++)
          {
          if(members[i]!=null)
          {
          sendPacket = new DatagramPacket(receivePacket.getData(),
          receivePacket.getLength(),members[i].address,members[i].port);
          socket.send( sendPacket );
          }
          }  // send packet to client

       } // end method sendPacketToClient

       // manipulates displayArea in the event-dispatch thread
       private void displayMessage( final String messageToDisplay )
       {
          SwingUtilities.invokeLater(
             new Runnable()
             {
                public void run() // updates displayArea
                {
                   displayArea.append( messageToDisplay ); // display message
                } // end method run
             } // end anonymous inner class
          ); // end call to SwingUtilities.invokeLater
       } // end method displayMessage
    @Override
    public void run()
    {
    // TODO Auto-generated method stub
    waitForPackets();
    }

    } // end class Server
    public class Client extends JFrame implements Runnable
    {
       private JTextField enterField; // for entering messages
       private JTextArea displayArea; // for displaying messages
       private DatagramSocket socket; // socket to connect to server
       String name;
       // set up GUI and DatagramSocket
       public Client(String myname)
       {
          super( myname );
          name = myname;
          enterField = new JTextField( "Type message here" );
          enterField.addActionListener(
             new ActionListener()
             {
                public void actionPerformed( ActionEvent event )
                {
                   try // create and send packet
                   {
                      // get message from textfield
                      String message = event.getActionCommand();
                 
                      byte data[] = message.getBytes(); // convert to bytes
            
                      // create sendPacket
                      DatagramPacket sendPacket = new DatagramPacket( data,
                         data.length, InetAddress.getLocalHost(), 5000 );
                      System.out.printf("send to server\"%s\"\n", new String(sendPacket.getData(),0,sendPacket.getLength()));
                      socket.send( sendPacket ); // send packet
                      enterField.setText("");
                   } // end try
                   catch ( IOException ioException )
                   {
                      displayMessage( ioException.toString() + "\n" );
                      ioException.printStackTrace();
                   } // end catch
                } // end actionPerformed
             } // end inner class
          ); // end call to addActionListener

          add( enterField, BorderLayout.NORTH );

          displayArea = new JTextArea();
          add( new JScrollPane( displayArea ), BorderLayout.CENTER );

          setSize( 400, 300 ); // set window size
          setVisible( true ); // show window

          try // create DatagramSocket for sending and receiving packets
          {
             socket = new DatagramSocket();
          } // end try
          catch ( SocketException socketException )
          {
             socketException.printStackTrace();
             System.exit( 1 );
          } // end catch
       } // end Client constructor

       // wait for packets to arrive from Server, display packet contents
       public void waitForPackets()
       {

          while ( true )
          {
             try // receive packet and display contents
             {
                byte data[] = new byte[ 100 ]; // set up packet
                DatagramPacket receivePacket = new DatagramPacket(
                   data, data.length );

                socket.receive( receivePacket ); // wait for packet
                System.out.println("receive from server ok");
                // display packet contents
                displayMessage(new String( receivePacket.getData(),
                      0, receivePacket.getLength() ) );
             } // end try
             catch ( IOException exception )
             {
                displayMessage( exception.toString() + "\n" );
                exception.printStackTrace();
             } // end catch
          } // end while
       } // end method waitForPackets

       // manipulates displayArea in the event-dispatch thread
       private void displayMessage( final String messageToDisplay )
       {
          SwingUtilities.invokeLater(
             new Runnable()
             {
                public void run() // updates displayArea
                {
                   displayArea.append( messageToDisplay );
                } // end method run
             }  // end inner class
          ); // end call to SwingUtilities.invokeLater
       } // end method displayMessage

    @Override
    public void run() {
    // TODO Auto-generated method stub
    waitForPackets();
    }
    }  // end class Client
    public class Member
    {
    int port;//端口号码
    InetAddress address;//地址
    Member(int port,InetAddress  address)
    {
    this.port = port;
    this.address = address;
    }
    }
    public class Member
    {
    int port;//端口号码
    InetAddress address;//地址
    Member(int port,InetAddress  address)
    {
    this.port = port;
    this.address = address;
    }
    }
  2. A
    Server.connetTo方法不对啊
    members[i] = new Member(Server.PORT_NUMBER, address);
    这里每个member的端口都是5000?显然不对了。这样等于server不停地在给自己5000端口发,再收,再发,死循环了。
    第一次client创建连接时,可以把自己的ip和端口先发给server。

apache ftpserver 使用 ssl启动时报错,求解决

  1. Q
    public class FtpServerTest {
    	public static void main(String[] args) {
    		try {
    		FtpServerFactory serverFactory= new FtpServerFactory();
    		ListenerFactory factory=new ListenerFactory();
    		factory.setPort(21);
    		SslConfigurationFactory ssl = new SslConfigurationFactory();
    		File keystoreFile=new File("D:\\up\\ftpserver.jks");
    		ssl.setKeystoreFile(keystoreFile);
    		ssl.setKeyPassword("password");
    		SslConfiguration sc=ssl.createSslConfiguration();
    		factory.setSslConfiguration(sc);
    		factory.setServerAddress("127.0.0.1");
    		factory.setImplicitSsl(true);
    		serverFactory.addListener("default", factory.createListener());
    		//serverFactory.setUserManager(ftpService.userManager());
    		FtpServer server = serverFactory.createServer();
    	
    			server.start();
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    }
    启动时一直报错
    log4j:WARN No appenders could be found for logger (org.apache.ftpserver.ssl.SslConfigurationFactory).
    log4j:WARN Please initialize the log4j system properly.
    org.apache.ftpserver.FtpServerConfigurationException: DefaultSsl.configure()
    	at org.apache.ftpserver.ssl.SslConfigurationFactory.createSslConfiguration(SslConfigurationFactory.java:364)
    	at FtpServerTest.main(FtpServerTest.java:22)
    Caused by: java.lang.NullPointerException
    	at org.apache.ftpserver.ssl.SslConfigurationFactory.loadStore(SslConfigurationFactory.java:305)
    	at org.apache.ftpserver.ssl.SslConfigurationFactory.createSslConfiguration(SslConfigurationFactory.java:326)
    	... 1 more
    
    

    问题补充:代码调试看,源代码报空指针的代码在下面
        private KeyStore loadStore(File storeFile, String storeType,
                String storePass) throws IOException, GeneralSecurityException {
            InputStream fin = null;
            try {
                if(storeFile.exists()) {
                    LOG.debug("Trying to load store from file");
                    fin = new FileInputStream(storeFile);
                } else {
                    LOG.debug("Trying to load store from classpath");
                    fin = getClass().getClassLoader().getResourceAsStream(storeFile.getPath());
                    
                    if(fin == null) {
                        throw new FtpServerConfigurationException("Key store could not be loaded from " + storeFile.getPath());
                    }
                }
                
                KeyStore store = KeyStore.getInstance(storeType);
                store.load(fin, storePass.toCharArray());
    
                return store;
            } finally {
                IoUtils.close(fin);
            }
        }

        
                KeyStore store = KeyStore.getInstance(storeType);
                store.load(fin, storePass.toCharArray());
    这里报异常
    问题补充:请问下对于源码如何去调试myali88 写道引用
    KeyStore store = KeyStore.getInstance(storeType);
                store.load(fin, storePass.toCharArray());
    这里报异常 
    


    具体是哪个对象空了,我想也应该能调试出来的。
  2. A
    引用
    KeyStore store = KeyStore.getInstance(storeType);
                store.load(fin, storePass.toCharArray());
    这里报异常 
    


    具体是哪个对象空了,我想也应该能调试出来的。

java socket 编程遇到的问题

  1. Q
    最近初步学习java socket 编程的时候遇到一个问题就是,当客户端向服务端发送数据时,会出现不能输入也不能,程序卡住的现象,尤其是中文,最多输入两行,控制台就不能再输入数据(客户端输入是用system.in来从键盘获取数据)。英文字符还好一些,但也会出现此种状况,百思不得其解!代码如下:
    
    
    server:
    package dragon.socket;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.ServerSocket;
    import java.net.Socket;

    public class MyServer {

    /**
    * @param args
    * @throws IOException
    */

    public static void main(String[] args) throws IOException {
    // TODO Auto-generated method stub
    ServerSocket ss = null;
    PrintWriter out = null;
    BufferedReader in = null;


    try {
    ss = new ServerSocket(1111);
    } catch (IOException e) {
    // TODO Auto-generated catch block
    System.err.println("could not listen port:1111");
    System.exit(1);
    e.printStackTrace();
    }
    Socket inComing = null;
    while(true){
    inComing = ss.accept();
    out = new PrintWriter(inComing.getOutputStream(),true);
    in = new BufferedReader(new InputStreamReader(inComing.getInputStream(),"GBK"));
    out.println("hello!....");
    out.println("enter BYE to exit");
    out.flush();

    while(true){
    String str = in.readLine();
    if(str==null){
    break;
    }
    else{
    out.println("Echo:"+str);
    System.out.println(str);
    out.flush();
    if(str.trim().equalsIgnoreCase("BYE")){
    break;
    }
    }
    }

    out.close();
    inComing.close();
    ss.close();
    }

    }

    }
    client:
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.Socket;
    import java.net.UnknownHostException;

    public class Client {
    public static void main(String[] args) throws IOException {
    Socket s = null;
    PrintWriter out = null;
    BufferedReader in = null;

    try {
    s = new Socket("localhost", 1111);
    out = new PrintWriter(s.getOutputStream(),true);
    in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    } catch (UnknownHostException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    System.out.println(in.readLine());
    System.out.println(in.readLine());
    BufferedReader stdln = new BufferedReader(new InputStreamReader(System.in));
    String userInput;
    while((userInput=stdln.readLine())!=null){
    out.println(userInput);
    System.out.println(in.readLine());
    }
    out.close();
    in.close();
    s.close();
    }


    }
    问题补充:fatherican 写道不要在服务器端进行相关的输入。仅仅是客户端发送,服务器接收后再返回发送消息
    你好,我仔细检查了一下代码,发现在服务器端没有把输入流“in”及时关闭,导致了问题的发生,已解决,还是谢谢你!
    问题补充:fatherican 写道不要在服务器端进行相关的输入。仅仅是客户端发送,服务器接收后再返回发送消息
    每次输入时都要必须把光标移到下一行,否则直接输入会在返回输入消息的前面出现英文字母。不知是何原因。
  2. A
    我想是因为,在客户端,你的输入对象是控制台,这个时候控制台就相当于一个记事本了,你想在什么地方输入,就在什么输入,当然是可以输入的地方。例如下一行和已经输入过的地方,因为这戏地方,都有了占位符,一旦你敲入回车键,那么就readLine了,接着就到服务器端了。

警告: No rules found matching 'Server/Service/Engine/Resource'.

  1. Q
    eclipse部署web工程包上面这错,咋回事呢,请牛人帮帮看。下面是server.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <Server port="8005" shutdown="SHUTDOWN">
      <Listener SSLEngine="on" className="org.apache.catalina.core.AprLifecycleListener"/>
      <Listener className="org.apache.catalina.core.JasperListener"/>
      <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/>
      <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener"/>
      <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/>
      <GlobalNamingResources>
        <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>

        <Resource auth="Container" driverClassName="com.mysql.jdbc.Driver" name="jdbc/jbpm" password="root" type="javax.sql.DataSource" url="jdbc:mysql://localhost:3306/studyjbpm" username="root"/>
      </GlobalNamingResources>
      <Service name="Catalina"> 
        <Connector address="localhost" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>

        <Connector address="localhost" port="8009" protocol="AJP/1.3" redirectPort="8443"/>
        <Engine defaultHost="localhost" name="Catalina">
          <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/>
          <Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true" xmlNamespaceAware="false" xmlValidation="false">
          <Context docBase="jbpm4_study" path="/jbpm4_study" reloadable="true" source="org.eclipse.jst.jee.server:jbpm4_study"/>
          </Host>
        </Engine>
      </Service>
    </Server>
    问题补充:yanq12 写道引用  <Resource auth="Container" driverClassName="com.mysql.jdbc.Driver" name="jdbc/jbpm" password="root" type="javax.sql.DataSource" url="jdbc:mysql://localhost:3306/studyjbpm" username="root"/>

    这个放到 Engine 里


    我吧这个放进去了,还是不行<Engine defaultHost="localhost" name="Catalina">
          <!-- Editable user database that can also be used by
               UserDatabaseRealm to authenticate users
          -->
         <!-- <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/> -->
          <Resource auth="Container" driverClassName="com.mysql.jdbc.Driver" name="jdbc/jbpm" password="root" type="javax.sql.DataSource" url="jdbc:mysql://localhost:3306/studyjbpm" username="root"/>

          <!-- Define the default virtual host
               Note: XML Schema validation will not work with Xerces 2.2.
           -->
          <Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true" xmlNamespaceAware="false" xmlValidation="false">
            <!--
              Current workaround for using the JBPM identity tables on Tomcat. Setting the Realm on
              the context with path /jbpm-console did not seem to work. Note that this workaround
              means that the complete localhost domain will use this realm !
            -->
          <Context docBase="jbpm4_study" path="/jbpm4_study" reloadable="true" source="org.eclipse.jst.jee.server:jbpm4_study"/>
          </Host>
        </Engine>
    问题补充:我用的是tomcat6.0.30,打出下面的日志:
    2011-11-22 9:41:49 org.apache.catalina.core.AprLifecycleListener init
    信息: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Genuitec\Common\binary\com.sun.java.jdk.win32.x86_1.6.0.013\bin;.;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.5.0_17/bin/client;C:/Program Files/Java/jre1.5.0_17/bin;%ANT_HOME%\bin;C:\Program Files\Common Files\NetSarang;C:\Program Files\Java\jre1.5.0_17\bin;E:\oracle\ora92\bin;C:\Program Files\Oracle\jre\1.3.1\bin;C:\Program Files\Oracle\jre\1.1.8\bin;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;D:\Program Files\TortoiseSVN\bin;C:\Program Files\Common Files\Adobe\AGL;C:\Program Files\StormII\Codec;C:\Program Files\StormII;C:\Program Files\CVSNT\;C:\Program Files\IDM Computer Solutions\UltraEdit\;F:\Program Files\apache-ant-1.8.2\bin
    2011-11-22 9:41:49 org.apache.tomcat.util.digester.Digester endElement
    警告:   No rules found matching 'Server/Service/Engine/Resource'.
    2011-11-22 9:41:49 org.apache.coyote.http11.Http11Protocol init
    信息: Initializing Coyote HTTP/1.1 on http-localhost%2F127.0.0.1-8080
    2011-11-22 9:41:49 org.apache.catalina.startup.Catalina load
    信息: Initialization processed in 390 ms
    2011-11-22 9:41:49 org.apache.catalina.realm.JAASRealm setContainer
    信息: Set JAAS app name Catalina
    2011-11-22 9:41:50 org.apache.catalina.core.StandardService start
    信息: Starting service Catalina
    2011-11-22 9:41:50 org.apache.catalina.core.StandardEngine start
    信息: Starting Servlet Engine: Apache Tomcat/6.0.30
    2011-11-22 9:41:50 org.apache.catalina.startup.HostConfig deployDescriptor
    信息: Deploying configuration descriptor jbpm4_study.xml
    2011-11-22 9:41:50 org.apache.coyote.http11.Http11Protocol start
    信息: Starting Coyote HTTP/1.1 on http-localhost%2F127.0.0.1-8080
    2011-11-22 9:41:50 org.apache.jk.common.ChannelSocket init
    信息: JK: ajp13 listening on localhost/127.0.0.1:8009
    2011-11-22 9:41:50 org.apache.jk.server.JkMain start
    信息: Jk running ID=0 time=0/16  config=null
    2011-11-22 9:41:50 org.apache.catalina.startup.Catalina start
    信息: Server startup in 312 ms
    问题补充:huoyj 写道你把Resources元素放到Context元素里面。
    楼主,放到context里没有了,No rules found matching 'Server/Service/Engine/Resource'.
    这个错,但是又出现一个新的问题。
    信息: Starting Servlet Engine: Apache Tomcat/6.0.30
    2011-11-22 10:44:55 org.apache.catalina.startup.HostConfig deployDescriptor
    信息: Deploying configuration descriptor jbpm4_study.xml
    2011-11-22 10:44:55 org.apache.catalina.core.NamingContextListener addResource
    严重: Failed to bind object: javax.naming.NamingException: Name is not valid
    那个属性的命名不规范呢,还是咋的呢
  2. A
    换个tomcat版本试试吧。

Java 如何调用sever端dll

  1. Q
    刚接触java就被要求调查这么难的问题...求高手指导
    问题如下:
    java的客户端,需要调用dll,但用native的方法好像不能成功,被告知因为dll在server端的缘故,现在需要查找其他方法,比如是否可以写个dll去调这个在server端的dll,或者java有其他方法可以使用。
    由于没接触过server,java也是刚接触,所以完全不懂,望指导。
  2. A
    引用java的客户端,需要调用dll,但用native的方法好像不能成功,被告知因为dll在server端的缘故,现在需要查找其他方法,比如是否可以写个dll去调这个在server端的dll,或者java有其他方法可以使用。
    由于没接触过server,java也是刚接触,所以完全不懂,望指导。

    server调用dll,client通过rmi调用server就好了

JAVA socket 传送文件一直被阻塞

  1. Q
    我写了一个简单的JAVA socket传送文件的程序如下:

    客户端:
    System.out.println("file download starts.");
    File fDir = new File("./downloads");
    File file = new File(fDir, "abc.txt");
    BufferedOutputStream bufr = new BufferedOutputStream(new FileOutputStream(file));
    byte[] line = new byte[102400];
    int chunkSize;
    while((chunkSize = in.read(line))!= -1){
    bufr.write(line, 0, chunkSize);
    bufr.flush();
    Thread.sleep(10);
    }
    bufr.close();
    System.out.println("file download completes");

    服务器端:
    File file = new File(fDir, fileName);
    BufferedInputStream buffile = new BufferedInputStream(new FileInputStream(file));
    byte[] line = new byte[102400];
    int chunkSize;
    System.out.println("file transmission start.");
    while ((chunkSize = buffile.read(line)) != -1) {
    out.write(line, 0, chunkSize);
    Thread.sleep(10);
    }
    buffile.close();
    System.out.println("file transmission complete.");

    结果服务器端可以正常打印出"file transmission complete.",但是客户端程序总会进入死循环。
    看起来好像是因为read是阻塞方法,但是始终接收不到服务器端发来的文件结束符
    于是就卡在了chunkSize = in.read(line))!= -1这条语句一样。
    而当我把程序强行结束掉,客户端下载的文件就立即出现在硬盘里了,而且无任何损坏。看起来客户端已经成功的接受了文件的所有部件,就是因为阻塞方法read不能返回-1而导致一直卡在那不动。
    不知道我这两段代码有什么错误,导致了这种奇怪的阻塞,求教啊!!谢谢
  2. A
    需要使用文件大小来结束while循环,首先Server发送文件大小给Client,Client在循环中判断接受到的数据长度的累加值是否等于文件长度,如果想等,则break;

java网络编程的疑问

  1. Q
    有一个问题请教一下,
    服务器端的ServerSocket接收数据的时候,
    当accept一个客户端的连接,
    然后开一个线程来接收数据,然后继续accept。
    就在第一个客户端数据还没传完的时候又有一个客户端来连接了,
    那么第二个客户端是在同一时间用同一个端口来接收数据的,
    会有问题吗?为什么呢?
    ps:如果没有问题的话,怎么知道在某一个时刻传来的数据是给第一个线程还是给第二个线程呢,后台是不是有个监控程序呢?
    谢谢
    问题补充:有一个问题请教一下,
    服务器端的ServerSocket接收数据的时候,
    当accept一个客户端的连接,
    然后开一个线程来接收数据,然后继续accept。
    就在第一个客户端数据还没传完的时候又有一个客户端来连接了,
    那么第二个客户端是在同一时间用同一个端口来接收数据的,
    会有问题吗?为什么呢?
    ps:如果没有问题的话,怎么知道在某一个时刻传来的数据是给第一个线程还是给第二个线程呢,后台是不是有个监控程序呢?
    谢谢
    问题补充:net.mail.public 写道引用就在第一个客户端数据还没传完的时候又有一个客户端来连接了,
    那么第二个客户端是在同一时间用同一个端口来接收数据的,
    会有问题吗?为什么呢?

    不会用同一个端口来和两个客户端来通信,从理论上讲也是讲不通的.如果用同一个端口和两个客户端通信,那要给其中一个客户端发信息时,怎么通过同一个端口来指定呢?

    希望对你有所帮助...
    你看这段程序应该就是使用的同一个端口:
    public class MultiJabberServer {  
      static final int PORT = 8080;
      public static void main(String[] args)
          throws IOException {
        ServerSocket s = new ServerSocket(PORT);
        System.out.println("Server Started");
        try {
          while(true) {
            // Blocks until a connection occurs:
            Socket socket = s.accept();
            try {
              new ServeOneJabber(socket);
            } catch(IOException e) {
              // If it fails, close the socket,
              // otherwise the thread will close it:
              socket.close();
            }
          }
        } finally {
          s.close();
        }
      } 
    }
    


    问题补充:net.mail.public 写道Server的代码(JDK1.5运行OK):
    package com.Test;
    
    import java.net.ServerSocket;
    import java.net.Socket;
    
    /*
     * created time:下午09:57:45
     * creator: Tian Zhichao ([email protected])
     *
     */
    public class Server {
    
    	/**
    	 * main() 2010-4-11,下午09:57:46
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		try {
    			ServerSocket server = new ServerSocket(8888);
    			while(true){
    				Socket client = server.accept();
    				new ManipulateClient(client).start();
    			}
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    	public void run(){
    		
    	}
    
    }
    class ManipulateClient extends Thread{
    	private Socket socket;
    	public ManipulateClient(Socket _socket){
    		this.socket = _socket;
    	}
    	public void run(){
    		System.out.println(socket.getRemoteSocketAddress());
    	}
    }
    
    

    Client的代码:
    package com.Test;
    
    import java.io.DataOutputStream;
    import java.io.OutputStream;
    import java.net.Socket;
    
    /*
     * created time:下午10:01:47
     * creator: Tian Zhichao ([email protected])
     *
     */
    public class Client {
    
    	/**
    	 * main() 2010-4-11,下午10:01:47
    	 */
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		try {
    			Socket client = new Socket("127.0.0.1",8888);
    			OutputStream os = client.getOutputStream();
    			DataOutputStream dos = new DataOutputStream(os);
    			dos.writeUTF("aaaa");
    			
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    	}
    
    }
    

    希望对你有所帮助...
    你好,你的程序也是使用的8888这个端口来接收数据的,当你的本地的客户端正在写数据到服务器端的时候,这时又有其他机器的客户端来连服务器,那么服务器会同时接收这两个客户端的数据吗?
    问题补充:net.mail.public 写道引用你好,你的程序也是使用的8888这个端口来接收数据的,当你的本地的客户端正在写数据到服务器端的时候,这时又有其他机器的客户端来连服务器,那么服务器会同时接收这两个客户端的数据吗?


    服务器是可以同时接收N个客户端的.每个客户端用一个线程来接收就可以了.

    就像现在的QQ,你以为你一个号码,人家给你一台机器在服务你的QQ哇?

    哦,那么怎么知道在某一个时刻传来的数据是给第一个线程还是给第二个线程呢,java的后台是不是有个监控程序呢?

    问题补充:net.mail.public 写道
    哦,那么怎么知道在某一个时刻传来的数据是给第一个线程还是给第二个线程呢,java的后台是不是有个监控程序呢?



    看来我给你刚才写的程序,你是没看或者没仔细看.或者没看明白吧...白费我的苦心了哦...



    你如果能明明白理解我刚才写的那两个程序,我想你就不会再有什么问题了.


    建议你最好找书好好看看TCP Socket编程模型吧...

    可能是我把问题的表述的不好,你回答的程序还是没有解决我的问题。不过还是谢谢你的回答
    问题补充:waterdh 写道每次Accept得到的socket对象都是一个新的对象,在传统的io网络框架里面,你需要针对每个socket对象来起一个单独的线程处理。
    比如:
      final Socket cs = server.accept();
      Thread th = new Thread(){
         public void run(){
             while(true){
                  //从客户那里读取数据
                 //处理数据
              }
             
         }
      };
    


    我这里为了简便,直接使用了内部类的方式,你可以另外写runnable接口或者从Thread继承。
    up!up!
    谢谢你的回答,
    还是没有真正解决我的问题,我不是要知道如何写这样的程序,而是想知道一个端口为什么可以同接收无数个连接。我估计是操作系统支持了这个功能,把这些连接存到了内存里。恩,应该是的。
  2. A
    哦,那么怎么知道在某一个时刻传来的数据是给第一个线程还是给第二个线程呢,java的后台是不是有个监控程序呢?



    看来我给你刚才写的程序,你是没看或者没仔细看.或者没看明白吧...白费我的苦心了哦...



    你如果能明明白理解我刚才写的那两个程序,我想你就不会再有什么问题了.


    建议你最好找书好好看看TCP Socket编程模型吧...