java socket 长连接奇怪的问题

我有一个类,负责通过SOCKET长连接与服务器端通讯。
这个循环读取一个队列来发送。
问题来了,在本类的MAIN方法中向队列中添加数据,就可以发送出去,在SERVLET中,通过HTTP请求添加,就是发送不出去!请大家帮忙看看,谢谢。下面是这个主要类的代码。

/**

  • */ package com.dianshangwang.lianhepayfront.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;

import org.apache.log4j.BasicConfigurator;
import org.apache.log4j.Logger;

import com.dianshangwang.lianhepayfront.global.Config;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

/**

  • @author lay
  • @date 2013年11月4日
    */
    public class IcardpayClient {
    private static Logger log = Logger.getLogger(IcardpayClient.class);
    private static Socket socket;
    private static BufferedReader reader;
    private static PrintWriter writer;
    private static Thread sendThread;
    private static Thread receiveThread;
    private static Thread monitorThread;

    private static boolean isRunning = false;

    /**

    • 心跳计数器 若此值与当前时间戳值小于60000则认定断线,进行重联操作 */ private static Long heartbeatTimestamp = System.currentTimeMillis();

    private static IcardpayClient instance = new IcardpayClient();

    private IcardpayClient() {
    }

    public static IcardpayClient getInstance() {
    return instance;
    }

    public static void main(String[] args) {
    BasicConfigurator.configure();
    IcardpayClient client = new IcardpayClient();
    client.start();

    MsgQueue.sendQueue.add("{\"agentNo\":\"A10342hp\",\"tradeType\":\"256\",\"sessionId\":\"1\"}");
    

    }

    public void start() {
    init();

    sendThread = new Thread(new SendThread());// 启动读线程
    receiveThread = new Thread(new ReceiveThread());// 启动收线程
    monitorThread = new Thread(new MonitorThread()); // 启动监视线程
    
    sendThread.setName("icardpay-send-thread");
    receiveThread.setName("icardpay-receive-thread");
    monitorThread.setName("icardpay-monitor-thread");
    

// sendThread.setDaemon(true);
// receiveThread.setDaemon(true);
// monitorThread.setDaemon(true);

    sendThread.start();
    log.info("SOCKET发送线程开启!");
    receiveThread.start();
    log.info("SOCKET接收线程开启!");
    // monitorThread.start();
    // log.info("SOCKET监视线程开启!");

}

public void restart() {
    stop();
    init();
}

public void stop() {
    isRunning = false;
}

private void init() {
    socket = new Socket();
    try {
        socket.setKeepAlive(true);
        socket.connect(new InetSocketAddress(Config.icardpayHost, Config.icardpayPort));
        reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
        writer = new PrintWriter(socket.getOutputStream());

        heartbeatTimestamp = System.currentTimeMillis();

        log.info("已创建与支付通的SOCKET连接!");

        isRunning = true;
    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public void write(String msg) {
    writer.println(msg);
    writer.flush();
    log.info(Thread.currentThread().getName() + "发送:" + msg);
}

private String read() throws IOException {
    String msg = reader.readLine();
    if (msg != null) {
        log.info("接收:" + msg);
    }
    return msg;
}

class SendThread implements Runnable {

    @Override
    public void run() {

        while (isRunning) {

            if (!MsgQueue.sendQueue.isEmpty()) {

                String v = MsgQueue.sendQueue.poll();

                write(v);
            }

            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

}

class ReceiveThread implements Runnable {

    @Override
    public void run() {
        while (isRunning) {

            String content = null;
            try {
                content = read();
            } catch (IOException e1) {
                log.error("SOCKET读取异常,将重新启动。。。", e1);
                restart();
                continue;
            }

            if (null == content || content == "") {
                continue;
            }

            JsonObject obj = new JsonParser().parse(content).getAsJsonObject();

            if (obj.has("tradeType") && "0".equals(obj.get("tradeType").getAsString())) {
                // 收到心跳包, 刷新计数器
                heartbeatTimestamp = System.currentTimeMillis();
                continue;
            }

            if (!obj.has("sessionId")) {
                log.info("收到未标识的包:" + obj.toString());
                continue;
            }

            String id = obj.get("sessionId").getAsString();

            if (MsgQueue.listeners.containsKey(id)) {
                MsgQueue.listeners.get(id).received(content);
                MsgQueue.listeners.remove(id);
            } else {
                log.info("接收到过期包:" + content);
            }

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // 忽略
            }

        }
    }

}

class MonitorThread implements Runnable {

    String heartbeat = "{\"agentNo\":\"A10342hp\",\"tradeType\":\"0\"}";

    @Override
    public void run() {
        while (isRunning) {
            if (System.currentTimeMillis() - heartbeatTimestamp >= 60000) {
                // SOCKET已失效
                restart();
            }

            // 发送心跳包
            write(heartbeat);

            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                // 忽略
            }
        }
    }

}

}

1个回答

我没怎么看代码但是你说读写的问题是不是会用到流,用流的时候要注意,对应创建。尤其在socket经过传递后,比如有一个函数的参数是socket,传到函数中建立流,那么对应的另一端也要从新建立,不能再用原来的了

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
Python+OpenCV计算机视觉

Python+OpenCV计算机视觉

Java Timer启动Socket问题

最近弄了个javaweb程序,想在web启动的时候用Timer 启动socket去连接服务端并等待服务端的消息 ,但是问题来了 可以成功连接但是总是有问题 爆出connection rest异常, 但是测试写的java直连服务端端口是可以正常发送接收消息的的,最奇怪的是,我这个报文还没收发完就报这个connection rest 异常了有时候是正read的时候报有的时候是wirte时候报异常,但是我数据库的链接却增加了许多而且这个链接一直被占着不释放,

java socket 无故当机

这是一个socket长连接的程序,代码如下。我是在windows命令窗口运行socket服务器的。如果有机器设备通过我规定好的代码请求服务器,我就给设备建立长连接进行通讯。然后如果有另外的客户端通过规定好的代码请求,我就发送指令给指定设备,然后设备返回信息,再返回给客户端,这种是短连接。但是很奇怪的就是,总有应该是网络的爬虫请求我的程序,总收到一些乱七八糟的字符串,但是因为这些字符串和我规定的不一样,所以是拦截在外面的,建立不了长连接。最麻烦的来了,当程序运行久了以后或者一定时间,我客户端请求服务器短连接就超时了,服务器命令窗口没显示信息,但是如果我ctrl+c结束一下,请求的字符串又能打印出来了了,好像整个程序挂起来没反应,以至于程序很不稳定,设备用久了总是要重启服务器程序才能恢复。新手socket,不知道是否有精通的大神,能解答一下。会不会是接收数据那段出现了问题呢,代码如下: class SocketThread implements Runnable { private Socket socket; public SocketThread(Socket socket) { this.socket = socket; } public void run() { InputStreamReader isr = null; BufferedReader br = null; OutputStreamWriter osr = null; BufferedWriter bw = null; try { isr = new InputStreamReader(socket.getInputStream()); br = new BufferedReader(isr); osr = new OutputStreamWriter(socket.getOutputStream()); bw = new BufferedWriter(osr); char[] chars = new char[1024]; int len; String resultMsg = ""; while((len = br.read(chars)) != -1){ if (1024 == len) { resultMsg += chars; } else { for (int i = 0; i < len; i++) { resultMsg += chars[i]; } resultMsg = resultMsg.trim(); System.out.println("data:"+resultMsg); /** * 新设备连接 */ if(resultMsg.indexOf("LSKJ:")!=-1){ // 下面这个方法是保存socket到map中 ConnectNew(resultMsg, socket, bw); } /** * 发送代码 */ if(resultMsg.indexOf("<CODE>")!=-1){ // 普通客户端连接 int tradeCode = Integer.parseInt(SocketUtil.getXMLData(resultMsg, "CODE")); switch (tradeCode) { case 100:// 100代码:往设备电路板发送指令 String command = SocketUtil.getXMLData(resultMsg, "COMMAND"); String deviceIp = SocketUtil.getXMLData(resultMsg, "IP");// IP地址 int devicePort = Integer.parseInt(SocketUtil.getXMLData(resultMsg, "PORT")); // 端口 Socket sourceSocket = socketMap.get(devicePort); clientMap.put(socket.getPort(), socket); Writer targetWriter = new OutputStreamWriter(sourceSocket.getOutputStream()); targetWriter.write(command+":LSYD:"+socket.getPort()); targetWriter.flush(); break; case 101:// 101代码:查询socket的数据 StringBuffer returnMsg = new StringBuffer(); if(!socketMap.isEmpty()){ for (Socket socket:socketMap.values()) { returnMsg.append(socket.getInetAddress().getHostAddress()).append(":").append(socket.getPort()); returnMsg.append("\n"); } }else{ returnMsg.append(" socketMap is null"); } bw.write(returnMsg.toString()); bw.flush(); break; default: break; } } /** * 响应代码 */ if(resultMsg.indexOf("LSYD:")!=-1){ /** * 返回例子: * OUDC1_??:LSYD:10001 OFF */ String[] msg = resultMsg.split(":"); if(msg.length>=2){ String returnCommand = resultMsg.split(":")[2]; if(returnCommand.length()>=4){ // 取出返回端口号 returnCommand = returnCommand.substring(0, 5); String regEx="[^0-9]"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(returnCommand); // 端口号 int clientPort = Integer.parseInt(m.replaceAll("").trim()); //System.out.println("端口号是:"+clientPort); // 返回结果 String result = resultMsg.substring(resultMsg.lastIndexOf(" ")+1,resultMsg.length()); //取出socket返回 Socket clientSocket = clientMap.get(clientPort); if(clientSocket!=null){ Writer targetWriter = new OutputStreamWriter(clientSocket.getOutputStream()); targetWriter.write(result); targetWriter.flush(); clientMap.remove(clientPort); } } } } } resultMsg =""; } } catch (IOException e) { e.printStackTrace(); } finally { } } } 代码解释一下,当有LSKJ:00001请求的话,服务器就建立长连接,同时保存了IP和端口了,然后如果有<CODE>100</CODE><COMMAND>OUDC1_??</COMMAND><IP>192.168.1.222</IP><PORT>55775</PORT>这种信息请求的话,我就知道是要发送给指定的设备,然后等待设备返回指令OUDC1_ON=030:LSYD:54498:OK,我就知道要返回给54498端口的客户端短连接数据了。

eclipse中的socket奇怪问题?

import java.net.*; import java.io.*; class SocketDemo { public static void main(String[] args) { try { Socket s = new Socket("192.168.2.119",10003); System.out.println(s.isConnected()); System.out.println("s="+s); } catch (Exception e1) { e1.printStackTrace(); } } } 首先,这个ip地址并不在局域网中存在,也没有一个服务端在监听10001端口,可是结果却是: true s=Socket[addr=/192.168.2.119,port=10003,localport=3642] 甚至把网络拔掉,结果也一样。 而我理解的socket的在建立对象时就已经去和服务单进行连接请求,如果服务端连接不上,会出现异常。 可是结果却是连接成功。 把这个java文件在DOS 命令行中,通过原始的javac编译在通过java运行,结果是: 网线未断开: java.net.ConnectException: Connection timed out: connect 网线断开: java.net.NoRouteToHostException: No route to host: connect 哪位兄弟可以解释一下,为什么在eclipse中却出现的是连接成功的结果呢?? 注:用的是同一个JDK.

安卓的socket编程的问题,很奇怪的问题

我想做一个微信练练手,客户端在androidstudio里面写客户端,在myeclipse写服务器, 同样的客户端,在myeclipse里面可以链接到服务器,但是在androidstudio里面却链接 不到myeclipse的服务器,这是为什么呢? myeclipse的服务器 package server; import java.io.IOException; import java.io.ObjectInputStream; import java.net.InetSocketAddress; import java.net.ServerSocket; import java.net.Socket; import comm.User; public class Wechat_server { public static void main(String[] args) { Wechat_server ws = new Wechat_server(); } public Wechat_server(){ try { ServerSocket ss = new ServerSocket(); ss.bind(new InetSocketAddress(8888)); System.out.println("服务器开启"); Socket a = ss.accept(); ObjectInputStream ois = new ObjectInputStream(a.getInputStream()); System.out.println("链上了"); User u = (User) ois.readObject(); System.out.println(u.getName().toString()+" "+u.getSex().toString()); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } androidstudio的客户端 package com.example.herjey.sock_test; import android.icu.text.LocaleDisplayNames; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.Toast; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.net.Socket; import comm.User; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void oo(View v){ conn c = new conn(); Thread t = new Thread(c); t.start(); } class conn implements Runnable{ @Override public void run() { try { Socket s = new Socket(" 192.168.108.1",8888); User i = new User(); i.setName("史迪克"); i.setSex("男"); ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream()); oos.writeObject(i); Log.d("thread_test","进来了"); } catch (IOException e) { e.printStackTrace(); } } } } 把客户端的socket代码放在myeclipse里面可以连接上客户端的

java rmi连接远程主机问题

问题是这样的,通过rmi来实现分布式通信,用的是20112端口,在本地实现的时候是没问题的,但是部署到主机(亚马逊云机,供外访问ip:54.**.72.52,内部IP是10.0.3.9,有防火墙,但是已经打开20112和20110端口),就不能访问了,错误 java.rmi.ConnectionException:Connetcion refused to host:10.0.3.9;nested exception: java.net.connetionException:connetion time out (我奇怪:外部ip既然能连上,怎么会卡到10.0.3.9那里啊,不应该是一台机子吗?) 然后我在网上找答案:他们说20112端口是rmi通信端口,而数据发送还需要一个端口,需重写一个类,然后我就写了: public class MyRMISocket extends RMISocketFactory { public Socket createSocket(String host, int port) throws IOException { System.out.println("client socket"+host+":"+port); return new Socket(host, port); } @Override public ServerSocket createServerSocket(int port) throws IOException { if (port == 0) { System.out.println("original port is 0"); port = 20110; //不指定就随机分配了 } // port=dataPort; System.out.println("prot"+port); return new ServerSocket(port); } } 按照网上的说法:指定20110来设置固定的端口来穿越防火墙,但是我设置之后,在本地测试的时候发现打印的log根本就没使用这个20110,还是rmi的我指定的那个端口20112,这是为什么,难道在一个网段里面不需要另起端口,还是我的理解有错误? 下面是我的服务端和客户端的连接代码 server: UpdateGatway gatway1=new UpdateGatwayImpl(); RMISocketFactory.setSocketFactory (new MyRMISocket()); System.setProperty("java.rmi.server.hostname", "54.**.72.52"); Registry registry1=LocateRegistry.createRegistry(20112); registry1.rebind("vernumberGW", gatway1); (用Naming绑定的时候出错,就用registry来绑定了) client: UpdateGatway gatway1 = (UpdateGatway) Naming.lookup("//54.**.72.52:20112/vernumberGW"); 如果放到局域网通信没问题,那个服务器是windows系统,我试了 system.setproperty("java.rmi.server.hostname","54.**.72.52") 重写RmiSocketFactory的方法 到现在都不行,只要放到服务器就报错,我在网上看到说要设置 host文件,我也试了,好像没效果,况且他们说的太笼统,我把服务器上的host文件也粘出来吧,大家看看是哪儿的问题, # #127.0.0.1 localhost 我把前面的注释去掉也不行,各位看看是哪儿的问题,如果是host文件的事,那么应该怎么改,谢~!

用Mina开发Socket服务器总有一些不可预知的奇怪现象?程序结束不了?!

最近在用 Java的Socket框架mina开发一个服务器端程序,服务器写完后,用mina的客户端API写了程序去连接服务器端,也连接成功了,但是发现每次客户端连接完成运行后 过1分钟客户端程序才结束! 经过调试发现代码已经执行了客户端代码的最后一行! 真是奇怪,客户端代码如下: <br /><pre name="code" class="java">public class Client { private static final String HOSTNAME = "localhost"; private static final int PORT = 20000; public static void main( String[] args ) throws Throwable { SocketConnector connector = new SocketConnector(); // Configure the service. SocketConnectorConfig cfg = new SocketConnectorConfig(); cfg.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new ObjectSerializationCodecFactory() ) ); cfg.getFilterChain().addLast( "logger", new LoggingFilter() ); IoSession session; try { ConnectFuture future = connector.connect(new InetSocketAddress( HOSTNAME, PORT), new ClientSessionHandler("Hi hi :("), cfg); future.join(); session = future.getSession(); } catch (RuntimeIOException e) { System.err.println("Failed to connect."); e.printStackTrace(); } // wait until the summation is done session.getCloseFuture().join(); System.out.println(session,"### all done! !"); } </pre> <br /> <br />"### all done!  !" 明明都已经打印出来了! 但是发现进程中还是有一个 javaw.exe! 而且用进程管理工具无法结束!,过了1分钟后,这个javaw.exe就没有了,发现eclipse的控制台红色结束按钮也变灰色了. 这些居然都是在最后一行代码执行完发生的? 感觉Java真是一个不稳定的东西~~<img src="/images/smiles/icon_confused.gif" /> <br /><strong>问题补充</strong><br />多谢回复,我看2.0是M版本,好像下载上面写着 unstable,所以没有用,你用这个版本感觉稳定吗?  我刚才又试验了一下 quickServer,试验socket连接到达100个居然就Connnectin refused了? 好像根本没有使用 非阻塞队列. mina虽然有我刚才说的问题,但是他却能坚持到 1000个连接没有发生 Connnectin refused的错误,说明他还是利用了线程池重用了很多连接,我现在马上试试 mina2.0! 我用的是1.1.7,connector没有dispose方法,那个例子我也看到了<br /><strong>问题补充</strong><br />还有你知道他的 httpserver怎么用吗? asyWeb合到mina里面了,我看了例子"httpserver",但是里面居然没有客户端调用示例.客户端怎么传递参数到http服务器也没有说明<br /><strong>问题补充</strong><br />我试了一下2.0M果然可以. 但是服务器端好像不能自己设置连接池了? 下面的代码在2.0不能用,你们怎么用连接池的? 我的性能是要求一台服务器机器需要有1000个并发连接. 我现在服务器这样写不知道有没有问题: <br /><pre name="code" class="java">ExecutorService executor = Executors.newFixedThreadPool(1000); IoAcceptor acceptor = new NioSocketAcceptor(); acceptor.setHandler( new TimeServerHandler() ); acceptor.getSessionConfig().setReadBufferSize( 2048 ); acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, 10 ); acceptor.getFilterChain().addLast("executor", new ExecutorFilter(executor)); acceptor.getFilterChain().addLast( "logger", new LoggingFilter() ); acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new ObjectSerializationCodecFactory() ) ); acceptor.bind( new InetSocketAddress(PORT) );</pre> <br /> <br />客户端很简单,就是模拟1000个并发连接: <br /><pre name="code" class="java"> public static void main( String[] args ) throws Throwable { for(int i=0;i&lt;1000;i++){ log.info("Enter run l..."+i); new Thread(new ClientThread(i)).start(); } } </pre> <br />每个客户端代码是: <br /><pre name="code" class="java">public void run() { // TODO Auto-generated method stub log.info("#### thread :"+this.num+" Running..."); NioSocketConnector connector = new NioSocketConnector(); // Configure the service. connector.setConnectTimeoutMillis(CONNECT_TIMEOUT); connector.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new ObjectSerializationCodecFactory() ) ); connector.getFilterChain().addLast( "logger", new LoggingFilter() ); connector.setHandler(new ClientSessionHandler(" hihi new!")); IoSession session; for (;;) { try { ConnectFuture future = connector.connect(new InetSocketAddress( HOSTNAME, PORT)); future.awaitUninterruptibly(); session = future.getSession(); break; } catch (Exception e) { System.err.println("Failed to connect."); e.printStackTrace(); } } // wait until the summation is done session.getCloseFuture().awaitUninterruptibly(); connector.dispose(); log.info("#### thread :"+this.num+" over ..."); }</pre> <br />不知道这样写是不是已经用了NIO特性和数量是1000的连接池了. 而且我发现客户端如果不用mina的API,直接用Socket API连接,服务器撑不到1000个,200多个就Connection refused了.<br /><strong>问题补充</strong><br />刚才试验了一下,模拟1000个客户端连接,成功了931个,异常是: <br /><pre name="code" class="java">2008-12-28 02:18:06,968 ERROR (LoggingFilter.java:127) - EXCEPTION : java.io.IOException: 您的主机中的软件放弃了一个已建立的连接。 at sun.nio.ch.SocketDispatcher.read0(Native Method) at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:25) at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:233) at sun.nio.ch.IOUtil.read(IOUtil.java:206) at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:207) at org.apache.mina.transport.socket.nio.NioProcessor.read(NioProcessor.java:180) at org.apache.mina.transport.socket.nio.NioProcessor.read(NioProcessor.java:42) at org.apache.mina.core.polling.AbstractPollingIoProcessor.read(AbstractPollingIoProcessor.java:568) at org.apache.mina.core.polling.AbstractPollingIoProcessor.process(AbstractPollingIoProcessor.java:547) at org.apache.mina.core.polling.AbstractPollingIoProcessor.process(AbstractPollingIoProcessor.java:539) at org.apache.mina.core.polling.AbstractPollingIoProcessor.access$400(AbstractPollingIoProcessor.java:57) at org.apache.mina.core.polling.AbstractPollingIoProcessor$Processor.run(AbstractPollingIoProcessor.java:867) at org.apache.mina.util.NamePreservingRunnable.run(NamePreservingRunnable.java:65) at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:650) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:675) at java.lang.Thread.run(Thread.java:595)</pre> <br />不知道调整哪些参数可以不发生这个错误? 就是说调整什么可以使1000个连接都能连上<br /><strong>问题补充</strong><br />windows需要修改OS的一个设置,但是设置了也不起作用,我再试试吧! java的NIO的目的是使服务器端打开尽量少的Socket连接,能处理尽可能多的客户端请求(不知道主要是非阻塞队列起作用还是那个concurrent线程池在发挥作用,应该是前者),这样理解没错吧?

很奇怪!加断点java执行的sql和不加断点执行的sql结果不一致!

我让其打印出来了一段sql,在plsql中执行,执行结果数据没问题,但是在java中执行出来的结果却是不同,但也不是完全不同,只是count(*) 的结果不一致

jdbc连接数据库的com.mysql.jdbc.CommunicationsException问题

我使用jdbc连接数据库,连接不上,上网搜了很多,有人说是数据库请求超时问题,也有说是数据库url,账号或者密码配置错误,我检查了都没有问题。还有一点奇怪的是,我用jdbc-odbc桥连接又可以连上数据库,用可视化工具也可以连上,但是用jdbc方式连接不上。。。我现在想着应该是哪里的配置有问题,请教各位大神,看看有谁知道或者遇到过,谢谢大家了 这是我的程序 ``` public static void main(String[] args) { Connection ct = null; Statement sm = null; ResultSet rs = null; try { //1、加载驱动(作用是把需要的驱动程序加入内存) Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //2、得到连接(指定连接到哪个数据源) //如果配置数据源选择的是Windows nt验证方式,则不需要用户名和密码 ct = DriverManager.getConnection("jdbc:odbc:MyTest", "root", "root"); //3、创建Statement或者PreparedStatement[区别] //Statement用处是,用于发送sql语句 sm = ct.createStatement(); //4、执行(crud、备份数据库、删除数据库......) //查询,显示所有部门信息 //ResultSet结果集,可以理解成一个表行的结果集 rs = sm.executeQuery("select * from dept"); //因为rs指向结果集的第一行的前一行, //循环取出 while (rs.next()) { int deptno = rs.getInt(1); String dname = rs.getString(2); String loc = rs.getString(3); System.out.println(deptno+" "+dname+" "+loc); } } catch(Exception e) { e.printStackTrace(); } finally { //关闭资源 //关闭顺序是谁后创建谁先关闭 try { //为了程序健壮 if (rs != null) { rs.close(); } if (sm != null) { sm.close(); } if (ct != null) { ct.close(); } } catch (SQLException e) { e.printStackTrace(); } } } ``` 这些是报的异常 ``` com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception: ** BEGIN NESTED EXCEPTION ** java.net.SocketException MESSAGE: Permission denied: recv failed STACKTRACE: java.net.SocketException: Permission denied: recv failed at java.net.SocketInputStream.socketRead0(Native Method) at java.net.SocketInputStream.read(SocketInputStream.java:152) at java.net.SocketInputStream.read(SocketInputStream.java:122) at com.mysql.jdbc.util.ReadAheadInputStream.fill(ReadAheadInputStream.java:105) at com.mysql.jdbc.util.ReadAheadInputStream.readFromUnderlyingStreamIfNecessary(ReadAheadInputStream.java:148) at com.mysql.jdbc.util.ReadAheadInputStream.read(ReadAheadInputStream.java:176) at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:1899) at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:481) at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:964) at com.mysql.jdbc.Connection.createNewIO(Connection.java:2544) at com.mysql.jdbc.Connection.<init>(Connection.java:1474) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:264) at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:146) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:195) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:184) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:200) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1086) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1073) at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:44) at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1810) at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:648) ** END NESTED EXCEPTION ** Last packet sent to the server was 0 ms ago. at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:552) at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:964) at com.mysql.jdbc.Connection.createNewIO(Connection.java:2544) at com.mysql.jdbc.Connection.<init>(Connection.java:1474) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:264) at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:146) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:195) at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:184) at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:200) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1086) at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1073) at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:44) at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1810) at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:648) ```

idea连接阿里云docker失败

通过tcp socket连接报错: ![图片说明](https://img-ask.csdn.net/upload/202004/10/1586482592_874892.jpg) 配置文件 ![图片说明](https://img-ask.csdn.net/upload/202004/10/1586482665_422845.jpg) 端口号 ![图片说明](https://img-ask.csdn.net/upload/202004/10/1586482701_452537.jpg) 阿里云安全组也添加了该端口号 奇怪的是第一次连接成功了,然后就这样了

在程序中连接mysql报错,急急急急

问题描述:我用Navicat可以正常的连接到数据库,但是通过程序连接的时候就报错如下,另外一个很奇怪的现象就是我再公司的时候连公司的网络就可以正常启动,回到家后连家里的网络就始终报错。在网上搜有一个相似的问题,可是我试了下还是不行。不知道问题出在哪里,求助. Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server. at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:422) at com.mysql.jdbc.Util.handleNewInstance(Util.java:408) at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1137) at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:674) at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1086) at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2508) at com.mysql.jdbc.ConnectionImpl.connectWithRetries(ConnectionImpl.java:2346) ... 93 more Caused by: java.net.SocketException: Connection reset at java.net.SocketInputStream.read(SocketInputStream.java:209) at java.net.SocketInputStream.read(SocketInputStream.java:141) at com.mysql.jdbc.util.ReadAheadInputStream.fill(ReadAheadInputStream.java:112) at com.mysql.jdbc.util.ReadAheadInputStream.readFromUnderlyingStreamIfNecessary(ReadAheadInputStream.java:159) at com.mysql.jdbc.util.ReadAheadInputStream.read(ReadAheadInputStream.java:187) at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:3158) at com.mysql.jdbc.MysqlIO.readPacket(MysqlIO.java:598) ... 96 more ``` ```

mongoDB使用studio 3T工具连接时为什么老是失败?

mongodb是装在本地得。通过黑窗口去连接是没什么问题得 ![图片说明](https://img-ask.csdn.net/upload/201905/07/1557214634_527464.jpg) 但是奇怪得来得,为什么用连接工具就连不上,工具是:studio 3T ![图片说明](https://img-ask.csdn.net/upload/201905/07/1557214684_638673.jpg) ![图片说明](https://img-ask.csdn.net/upload/201905/07/1557214701_839863.jpg)

奇怪的MySQL连接错误

<div class="post-text" itemprop="text"> <p>I am working with phpmyadmin version 4.4.15.7. DB server MariaDB 5.5.47 localhost via unix socket utf-8. Webserver apache 2.4.6. Php version 5.4.16. Originally this code worked well running with cpanel but recently I switched to vestacp running .9.8-16. connection credentials seem to be correct. Error is thrown after using mysqli_connect function:</p> <blockquote> <p>Failed to connect to MySQL: php_network_getaddresses: getaddrinfo failed: Name or service not known</p> </blockquote> <p>Here is my php file--redacted a little for security purposes. The first echo statement is the one thrown.</p> <pre><code>&lt;?php $sql = "SELECT * FROM Staff"; // Create connection $con=mysqli_connect(‘localhost',’pil_pil’,’pass_password’,’db_db’); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } // Check if there are results if ($result = mysqli_query($con, $sql)) { // If so, then create a results array and a temporary one // to hold the data $resultArray = array(); $tempArray = array(); // Loop through each row in the result set while($row = $result-&gt;fetch_object()) { // Add each row into our results array $tempArray = $row; array_push($resultArray, $tempArray); } // Finally, encode the array to JSON and output the results echo json_encode($resultArray); } // Close connections mysqli_close($con); ?&gt; </code></pre> </div>

两个应用访问同一个数据库,两个用户名和密码不一样,已确认两个用户名和密码都正确(plsql都可以登录),但是其中一个始终无法连接数据库。

很奇怪的问题,两个应用访问同一个数据库,两个用户名和密码不一样,已确认两个用户名和密码都正确(plsql都可以登录),但是其中一个始终无法连接数据库,有以下错误。求大神指点一下,很急~ Error querying database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is java.sql.SQLException: Unable to open a test connection to the given database. JDBC url = jdbc:oracle:thin:@192.168.65.33:11521:orcl, username = user. Terminating connection pool. Original Exception: ------ java.sql.SQLException: No more data to read from socket.

ssm框架运维报错(数据库连接时出错)

今早发现了一个很奇怪的东西,服务器上前后测试了好几次的程序突然崩了,之前运行非常稳定,这是报错,目标是我数据库,大家有没有懂的 ``` 27-Mar-2018 07:34:41.680 严重 [https-jsse-nio2-443-exec-2] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.RecoverableDataAccessException: ### Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 32,986,781 milliseconds ago. The last packet sent successfully to the server was 32,986,781 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem. ### The error may exist in file [C:\Program Files\Apache Software Foundation\Tomcat 9.0_Tomcat9.0\webapps2\ShowHTML\WEB-INF\classes\mapper\student_infoMapper.xml] ### The error may involve com.cn.fenyu.dao.student_infoMapper.selectByExample-Inline ### The error occurred while setting parameters ### SQL: select studentID, studentpw, power, studentname from student WHERE ( studentID = ? ) ### Cause: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 32,986,781 milliseconds ago. The last packet sent successfully to the server was 32,986,781 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem. ; SQL []; The last packet successfully received from the server was 32,986,781 milliseconds ago. The last packet sent successfully to the server was 32,986,781 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 32,986,781 milliseconds ago. The last packet sent successfully to the server was 32,986,781 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.] with root cause java.net.SocketException: Software caused connection abort: socket write error at java.net.SocketOutputStream.socketWrite0(Native Method) at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:111) at java.net.SocketOutputStream.write(SocketOutputStream.java:155) at java.io.BufferedOutputStream.flushBuffer(BufferedOutputStream.java:82) at java.io.BufferedOutputStream.flush(BufferedOutputStream.java:140) at com.mysql.jdbc.MysqlIO.send(MysqlIO.java:3964) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2596) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2776) at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2838) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2082) at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1307) at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.execute(NewProxyPreparedStatement.java:989) at org.apache.ibatis.executor.statement.PreparedStatementHandler.query(PreparedStatementHandler.java:63) at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:79) at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:63) at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:324) at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:156) at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:109) at com.github.pagehelper.PageInterceptor.intercept(PageInterceptor.java:141) at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:61) at com.sun.proxy.$Proxy111.query(Unknown Source) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148) at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141) at sun.reflect.GeneratedMethodAccessor72.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:433) at com.sun.proxy.$Proxy45.selectList(Unknown Source) at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:230) at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:137) at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:75) at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59) at com.sun.proxy.$Proxy46.selectByExample(Unknown Source) at com.cn.fenyu.servies.MainServies.finduser(MainServies.java:34) at com.cn.fenyu.controller.MainController.indexshow(MainController.java:149) at sun.reflect.GeneratedMethodAccessor90.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:498) at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205) at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133) at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:116) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) at javax.servlet.http.HttpServlet.service(HttpServlet.java:634) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) at javax.servlet.http.HttpServlet.service(HttpServlet.java:741) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ```

小弟有一个问题很急啊

就是我有一个JSp空间 我获取数据库连接的时候会报错 我最初认为是我的数据库连接池写得有问题 但是我后来用jdbc来获取连接出现一样的问题 下面是异常代码 com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception: ** BEGIN NESTED EXCEPTION ** com.mysql.jdbc.CommunicationsException MESSAGE: Communications link failure due to underlying exception: ** BEGIN NESTED EXCEPTION ** java.net.SocketException MESSAGE: Connection reset STACKTRACE: java.net.SocketException: Connection reset at java.net.SocketInputStream.read(SocketInputStream.java:168) at com.mysql.jdbc.util.ReadAheadInputStream.fill(ReadAheadInputStream.java:113) at com.mysql.jdbc.util.ReadAheadInputStream.readFromUnderlyingStreamIfNecessary(ReadAheadInputStream.java:160) at com.mysql.jdbc.util.ReadAheadInputStream.read(ReadAheadInputStream.java:188) at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:1994) at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2411) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2916) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723) at com.mysql.jdbc.Connection.execSQL(Connection.java:3250) at com.mysql.jdbc.Connection.setAutoCommit(Connection.java:5395) at com.mysql.jdbc.Connection.initializePropsFromServer(Connection.java:4118) at com.mysql.jdbc.Connection.createNewIO(Connection.java:2762) at com.mysql.jdbc.Connection.<init>(Connection.java:1553) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285) at java.sql.DriverManager.getConnection(DriverManager.java:582) at java.sql.DriverManager.getConnection(DriverManager.java:185) at com.mmx.db.DbConnection.getConnection(DbConnection.java:45) at com.mmx.RepeatCheck.doPost(RepeatCheck.java:45) at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Thread.java:619) ** END NESTED EXCEPTION ** Last packet sent to the server was 47 ms ago. STACKTRACE: com.mysql.jdbc.CommunicationsException: Communications link failure due to underlying exception: ** BEGIN NESTED EXCEPTION ** java.net.SocketException MESSAGE: Connection reset STACKTRACE: java.net.SocketException: Connection reset at java.net.SocketInputStream.read(SocketInputStream.java:168) at com.mysql.jdbc.util.ReadAheadInputStream.fill(ReadAheadInputStream.java:113) at com.mysql.jdbc.util.ReadAheadInputStream.readFromUnderlyingStreamIfNecessary(ReadAheadInputStream.java:160) at com.mysql.jdbc.util.ReadAheadInputStream.read(ReadAheadInputStream.java:188) at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:1994) at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2411) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2916) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723) at com.mysql.jdbc.Connection.execSQL(Connection.java:3250) at com.mysql.jdbc.Connection.setAutoCommit(Connection.java:5395) at com.mysql.jdbc.Connection.initializePropsFromServer(Connection.java:4118) at com.mysql.jdbc.Connection.createNewIO(Connection.java:2762) at com.mysql.jdbc.Connection.<init>(Connection.java:1553) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285) at java.sql.DriverManager.getConnection(DriverManager.java:582) at java.sql.DriverManager.getConnection(DriverManager.java:185) at com.mmx.db.DbConnection.getConnection(DbConnection.java:45) at com.mmx.RepeatCheck.doPost(RepeatCheck.java:45) at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Thread.java:619) ** END NESTED EXCEPTION ** Last packet sent to the server was 47 ms ago. at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2622) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2916) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723) at com.mysql.jdbc.Connection.execSQL(Connection.java:3250) at com.mysql.jdbc.Connection.setAutoCommit(Connection.java:5395) at com.mysql.jdbc.Connection.initializePropsFromServer(Connection.java:4118) at com.mysql.jdbc.Connection.createNewIO(Connection.java:2762) at com.mysql.jdbc.Connection.<init>(Connection.java:1553) at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:285) at java.sql.DriverManager.getConnection(DriverManager.java:582) at java.sql.DriverManager.getConnection(DriverManager.java:185) at com.mmx.db.DbConnection.getConnection(DbConnection.java:45) at com.mmx.RepeatCheck.doPost(RepeatCheck.java:45) at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:286) at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:845) at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583) at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447) at java.lang.Thread.run(Thread.java:619) ** END NESTED EXCEPTION ** Last packet sent to the server was 0 ms ago. 这个是程序代码 Connection con=null; try {Class.forName("com.mysql.jdbc.Driver"); con=DriverManager.getConnection("jdbc:mysql://****/yyqnew2?useUnicode=true&characterEncoding=utf8","****","******"); } catch(Exception e) { e.printStackTrace(); } 希望大家帮帮忙啊 [b]问题补充:[/b] 慢烦能说得详细些吗 我也感觉很奇怪啊 [b]问题补充:[/b] 我用c3p0尝试了的能建立连接池 但是有时候获取不到连接 有时候却能获取连接 感觉好像是mysql server不太稳定样 [b]问题补充:[/b] 你好 感谢你回答 主要是我所有分就只有这5分了 没有分了所以就只有给这5分了 我在本机用Php来连接数据库每次都成功 但是用Java来连接 偶尔能成功 经常报上面的错误 下面是php成功截图 [b]问题补充:[/b] 你好 你看图片没有啊 我就是直接用jdbc连接的啊 我还是用本机应用程序方式连接的 谢谢 try { Class.forName("com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql://*****/yyqnew2?useUnicode=true&characterEncoding=utf8","****","*****"); out.println(con); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery("select username from user_info limit 100"); while(rs.next()) { out.println(rs.getString(1)); } } catch (Exception e) { out.println(e); } finally { try { rs.close(); stmt.close(); con.close(); } catch(Exception e) { out.println(e); } } [b]问题补充:[/b] com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure. 这个好像是说和MySQL的通信连接失败 [b]问题补充:[/b] 呵呵 那个是我补充问题的时候写错了 程序没有写错 呵呵 [b]问题补充:[/b] 我连接串什么地方写错了啊? 请明确说明啊 谢谢 [b]问题补充:[/b] 你好 我没有写端口啊 比如这样的 jdbc:mysql://www.google.com/databasename 这样的url有错误吗

很奇怪的一个问题

SocketAcceptor acceptor=new NioSocketAcceptor(); 这句话会报以下异常谁遇到过,帮忙解决一下,谢谢! 代码: private static final int PORT = 8080; public static void main(String[] orgs) throws Exception { // 监听即将到来的TCP连接 SocketAcceptor acceptor=new NioSocketAcceptor(); } 异常信息: SLF4J: This version of SLF4J requires log4j version 1.2.12 or later. See also http://www.slf4j.org/codes.html#log4j_version [JRockit] ERROR: The JVM has crashed. Writing crash information to D:\Work\webpro\jrockit.2788.dump. ===== BEGIN DUMP ============================================================= JRockit dump produced after 0 days, 00:00:07 on Wed Nov 23 13:59:02 2011 ************************************************************************** * If you see this dump, please go to * * http://download.oracle.com/docs/cd/E15289_01/go2troubleshooting.html * * for troubleshooting information. * ************************************************************************** Additional information is available in: D:\Work\webpro\jrockit.2788.dump D:\Work\webpro\jrockit.2788.mdmp Error Message: Illegal memory access. [54] Exception Rec: EXCEPTION_ACCESS_VIOLATION (c0000005) at 0x009F00E2 - memory at 0x00000014 could not be read. Minidump : Wrote mdmp. Size is 138MB SafeDllMode : -1 Version : Oracle JRockit(R) R28.0.0-679-130297-1.6.0_17-20100312-2123-windows-ia32 CPU : Intel Core 2 SSE SSE2 SSE3 SSSE3 Core Intel64 Number CPUs : 2 Tot Phys Mem : 2072788992 (1976 MB) OS version : Microsoft Windows XP version 5.1 Service Pack 3 (Build 2600) (32-bit) Thread System: Windows Threads Java locking : Lazy unlocking enabled (class banning) (transfer banning) State : JVM is running Command Line : -Dfile.encoding=UTF-8 -Xbootclasspath/a:C:\Program Files\Genuitec\Common\plugins\com.genuitec.eclipse.j2eedt.core_8.6.0.me201007292038\data\libraryset\EE_5\javaee.jar;C:\Program Files\Genuitec\Common\plugins\com.genuitec.eclipse.j2eedt.core_8.6.0.me201007292038\data\libraryset\EE_5\jsf-impl.jar;C:\Program Files\Genuitec\Common\plugins\com.genuitec.eclipse.j2eedt.core_8.6.0.me201007292038\data\libraryset\EE_5\jsf-api.jar;C:\Program Files\Genuitec\Common\plugins\com.genuitec.eclipse.j2eedt.core_8.6.0.me201007292038\data\libraryset\EE_5\jstl-1.2.jar -Dsun.java.launcher=SUN_STANDARD iosession.MinaTimeServer Repository : java.home : D:\Work\javaJDK\jrmc-4.0.0-1.6.0\jre j.class.path : D:\Work\webpro\WebRoot\WEB-INF\classes;D:\Work\webpro\WebRoot\WEB-INF\lib\antlr-2.7.6.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\aopalliance-1.0.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\aspectjweaver.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\c3p0-0.9.1.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\cglib-2.2.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\commons-beanutils-1.7.0.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\commons-collections-3.1.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\commons-fileupload-1.2.2.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\commons-httpclient.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\commons-io-2.0.1.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\commons-lang-2.5.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\commons-logging.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\dom4j-1.6.1.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\ezmorph-1.0.3.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\freemarker-2.3.16.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\handsome-ipaddress-bin.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\hazelcast-1.9.2.3.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\hibernate-jpa-2.0-api-1.0.1.Final.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\hibernate3.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\javassist-3.12.0.GA.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\json-lib-2.1-jdk15.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\jta-1.1.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\mysqldriver.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\ognl-3.0.1.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\org.springframework.aop-3.1.0.M2.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\org.springframework.asm-3.1.0.M2.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\org.springframework.aspects-3.1.0.M2.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\org.springframework.beans-3.1.0.M2.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\org.springframework.context-3.1.0.M2.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\org.springframework.core-3.1.0.M2.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\org.springframework.expression-3.1.0.M2.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\org.springframework.jdbc-3.1.0.M2.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\org.springframework.orm-3.1.0.M2.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\org.springframework.transaction-3.1.0.M2.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\org.springframework.web-3.1.0.M2.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\slf4j-api-1.5.8.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\slf4j-log4j12-1.5.8.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\struts2-core-2.2.3.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\struts2-json-plugin-2.2.3.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\struts2-junit-plugin-2.2.3.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\struts2-spring-plugin-2.2.3.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\xwork-core-2.2.3.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\log4j-1.2.6.jar;C:\Program Files\Genuitec\Common\plugins\com.genuitec.eclipse.ws.xfire_8.6.0.me201007281000\lib\webservices-api.jar;C:\Program Files\Genuitec\Common\plugins\com.genuitec.eclipse.ws.xfire_8.6.0.me201007281000\lib\webservices-extra-api.jar;C:\Program Files\Genuitec\Common\plugins\com.genuitec.eclipse.ws.xfire_8.6.0.me201007281000\lib\webservices-extra.jar;C:\Program Files\Genuitec\Common\plugins\com.genuitec.eclipse.ws.xfire_8.6.0.me201007281000\lib\webservices-rt.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\axis-ant.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\axis.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\wsdl4j-1.5.1.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\commons-discovery-0.2.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\jaxen-1.1-beta-6.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\commons-codec-1.4.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\mina-core-2.0.4.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\mina-integration-beans-2.0.4.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\mina-filter-compression-2.0.4.jar;D:\Work\webpro\WebRoot\WEB-INF\lib\mina-example-2.0.4.jar j.lib.path : D:\Work\javaJDK\jrmc-4.0.0-1.6.0\bin;.;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Genuitec/Common/binary/com.sun.java.jdk.win32.x86_1.6.0.013/jre/bin/client;C:/Program Files/Genuitec/Common/binary/com.sun.java.jdk.win32.x86_1.6.0.013/jre/bin;C:\Documents and Settings\All Users\IMP2POcx;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;;E:\Program Files\IDM Computer Solutions\UltraEdit-32;D:\Work\apache-ant-1.8.2\bin JAVA_HOME : <not set> _JAVA_OPTIONS: <not set> PATH : C:/Program Files/Genuitec/Common/binary/com.sun.java.jdk.win32.x86_1.6.0.013/jre/bin/client;C:/Program Files/Genuitec/Common/binary/com.sun.java.jdk.win32.x86_1.6.0.013/jre/bin;C:\Documents and Settings\All Users\IMP2POcx;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;;E:\Program Files\IDM Computer Solutions\UltraEdit-32;D:\Work\apache-ant-1.8.2\bin StackOverFlow: 0 StackOverFlowErrors have occured OutOfMemory : 0 OutOfMemoryErrors have occured C Heap : Good; no memory allocations have failed GC Strategy : Mode: throughput, with strategy: genparpar (basic strategy: genparpar) GC Status : OC is not running. Last finished OC was OC#0. : YC is not running. Last finished YC was YC#0. YC History : Ran 0 YCs since last OC. Heap Holes : 1 hole(s), at 0x04B00000 - 0x1F860000 Heap : 0x02400000 - 0x21160000 (Size: 64 MB) Compaction : (no compaction area) NurseryList : 0x02400000 - 0x04400000 KeepArea : 0x03BFFFE8 - 0x04400000 KA Markers : [ 0x033FFFF0, 0x03BFFFE8 , 0x04400000 ] Forbidden A : (none) Previous KA : (none) Previous FA : (none) CompRefs : References are 32-bit. Registers (from ThreadContext: 0x00DCF744: eax = 00000000 ecx = 00000000 edx = 027a9960 ebx = 00dcfb00 esp = 00dcfa10 ebp = 00dcfa58 esi = 00c358a0 edi = 00000000 es = 00000023 cs = 0000001b ss = 00000023 ds = 00000023 fs = 0000003b gs = 00000000 eip = 009f00e2 eflags = 00010206 Loaded modules: (* denotes the module where the exception occured) 00400000-00434fff D:\Work\javaJDK\jrmc-4.0.0-1.6.0\bin\javaw.exe 7c920000-7c9b5fff C:\WINDOWS\system32\ntdll.dll 7c800000-7c91dfff C:\WINDOWS\system32\kernel32.dll 77d10000-77d9ffff C:\WINDOWS\system32\USER32.dll 77ef0000-77f38fff C:\WINDOWS\system32\GDI32.dll 77da0000-77e48fff C:\WINDOWS\system32\ADVAPI32.dll 77e50000-77ee2fff C:\WINDOWS\system32\RPCRT4.dll 77fc0000-77fd0fff C:\WINDOWS\system32\Secur32.dll 76300000-7631cfff C:\WINDOWS\system32\IMM32.DLL 62c20000-62c28fff C:\WINDOWS\system32\LPK.DLL 73fa0000-7400afff C:\WINDOWS\system32\USP10.dll 7c340000-7c395fff D:\Work\javaJDK\jrmc-4.0.0-1.6.0\jre\bin\msvcr71.dll 00850000-00b44fff *D:\Work\javaJDK\jrmc-4.0.0-1.6.0\jre\bin\jrockit\jvm.dll 71a20000-71a36fff C:\WINDOWS\system32\WS2_32.dll 77be0000-77c37fff C:\WINDOWS\system32\msvcrt.dll 71a10000-71a17fff C:\WINDOWS\system32\WS2HELP.dll 76b10000-76b39fff C:\WINDOWS\system32\WINMM.dll 10000000-1003afff D:\Work\javaJDK\jrmc-4.0.0-1.6.0\jre\bin\osal.dll 00c40000-00c72fff D:\Work\javaJDK\jrmc-4.0.0-1.6.0\jre\bin\util.dll 724c0000-72517fff C:\WINDOWS\system32\pdh.dll 76320000-76366fff C:\WINDOWS\system32\comdlg32.dll 5d170000-5d209fff C:\WINDOWS\system32\COMCTL32.dll 7d590000-7dd83fff C:\WINDOWS\system32\SHELL32.dll 77f40000-77fb5fff C:\WINDOWS\system32\SHLWAPI.dll 765e0000-76672fff C:\WINDOWS\system32\CRYPT32.dll 76db0000-76dc1fff C:\WINDOWS\system32\MSASN1.dll 73540000-7357cfff C:\WINDOWS\system32\ODBC32.dll 4b4f0000-4b4f5fff C:\WINDOWS\system32\odbcbcp.dll 77bd0000-77bd7fff C:\WINDOWS\system32\VERSION.dll 76990000-76acdfff C:\WINDOWS\system32\ole32.dll 770f0000-7717afff C:\WINDOWS\system32\OLEAUT32.dll 77180000-77282fff C:\WINDOWS\WinSxS\x86_Microsoft.Windows.Common-Controls_6595b64144ccf1df_6.0.2600.6028_x-ww_61e65202\comctl32.dll 1f840000-1f856fff C:\WINDOWS\system32\odbcint.dll 5e8e0000-5e8ecfff C:\WINDOWS\system32\perfproc.dll 5e8f0000-5e8f8fff C:\WINDOWS\system32\perfos.dll 015d0000-015f9fff D:\Work\javaJDK\jrmc-4.0.0-1.6.0\jre\bin\jfr.dll 6d860000-6d86bfff D:\Work\javaJDK\jrmc-4.0.0-1.6.0\jre\bin\verify.dll 6d3e0000-6d3fefff D:\Work\javaJDK\jrmc-4.0.0-1.6.0\jre\bin\java.dll 6d340000-6d347fff D:\Work\javaJDK\jrmc-4.0.0-1.6.0\jre\bin\hpi.dll 6d8a0000-6d8aefff D:\Work\javaJDK\jrmc-4.0.0-1.6.0\jre\bin\zip.dll 76bc0000-76bcafff C:\WINDOWS\system32\psapi.dll 6d6e0000-6d6e8fff D:\Work\javaJDK\jrmc-4.0.0-1.6.0\jre\bin\nio.dll 6d6c0000-6d6d2fff C:\Program Files\Genuitec\Common\binary\com.sun.java.jdk.win32.x86_1.6.0.013\jre\bin\net.dll 08950000-08962fff D:\Work\javaJDK\jrmc-4.0.0-1.6.0\jre\bin\net.dll 719c0000-719fdfff C:\WINDOWS\system32\mswsock.dll 60fd0000-61024fff C:\WINDOWS\system32\hnetcfg.dll 71a00000-71a07fff C:\WINDOWS\System32\wshtcpip.dll 089b0000-089c7fff D:\Work\javaJDK\jrmc-4.0.0-1.6.0\jre\bin\orii.dll 68000000-68035fff C:\WINDOWS\system32\rsaenh.dll 759d0000-75a7efff C:\WINDOWS\system32\USERENV.dll 5fdd0000-5fe24fff C:\WINDOWS\system32\netapi32.dll 089e0000-08af2fff D:\Work\javaJDK\jrmc-4.0.0-1.6.0\jre\bin\dbghelp.dll Stack: (* marks the word pointed to by the stack pointer) 00dcfa10: 00863bb6* 00dcfb00 00000000 a6c5fa24 00dcfb00 00c3599c 00dcfa28: 00dcfb00 00dcfa38 088bfd4e 00c358c8 00000000 00a0fc90 00dcfa40: 00dcfa1c 00dcf624 00dcff14 00a3c1f0 a6b3592c 00000000 00dcfa58: 00dcfa88 6d6c7f98 00000000 00dcfb00 00000000 00dcfb00 Code: (* marks the word pointed to by the instruction pointer) 009f00b0: 0424448b 0b74c085 0c244c8b 0824548b c3100c89 cccccccc 009f00c8: cccccccc cccccccc 0424448b 0474c085 02eb108b 448bd233 009f00e0: 40f60824* 488b0814 8b0a7410 68408b00 008bc103 0a048bc3 009f00f8: ccccccc3 cccccccc 0424448b 0474c085 02eb108b 448bd233 Last optimized methods: No methods optimized. Thread: "Main Thread" id=1 idx=0x4 tid=2400 lastJavaFrame=0x00DCFAE8 Stack 0: start=0x00D90000, end=0x00DD0000, guards=0x00D93000 (ok), forbidden=0x00D91000 Thread Stack Trace: at javaHandleLoadIntField+18(javafields.c:175+18)@0x009F00E2 at jni_GetIntField+390(jni.c:514+390)@0x00863BB6 at _NET_InetAddressToSockaddr@24+30()@0x6D6C7F98 at _Java_sun_nio_ch_Net_bind@20+36()@0x6D6E2540 -- Java stack -- at sun/nio/ch/Net.bind(Ljava/io/FileDescriptor;Ljava/net/InetAddress;I)V(Native Method) at sun/nio/ch/ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:119) at sun/nio/ch/ServerSocketAdaptor.bind(ServerSocketAdaptor.java:59) at sun/nio/ch/ServerSocketAdaptor.bind(ServerSocketAdaptor.java:52) at sun/nio/ch/PipeImpl$Initializer.run(PipeImpl.java:72) at jrockit/vm/AccessController.doPrivileged(AccessController.java:254) at jrockit/vm/AccessController.doPrivileged(AccessController.java:268) at sun/nio/ch/PipeImpl.<init>(PipeImpl.java:122) at sun/nio/ch/SelectorProviderImpl.openPipe(SelectorProviderImpl.java:27) at java/nio/channels/Pipe.open(Pipe.java:133) at sun/nio/ch/WindowsSelectorImpl.<init>(WindowsSelectorImpl.java:40) at sun/nio/ch/WindowsSelectorProvider.openSelector(WindowsSelectorProvider.java:26) at java/nio/channels/Selector.open(Selector.java:209) at org/apache/mina/transport/socket/nio/NioProcessor.<init>(NioProcessor.java:59) at jrockit/vm/RNI.c2java(IIIII)V(Native Method) at jrockit/vm/Reflect.invokeMethod(Ljava/lang/Object;Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;(Native Method) at sun/reflect/NativeConstructorAccessorImpl.newInstance0(Ljava/lang/reflect/Constructor;[Ljava/lang/Object;)Ljava/lang/Object;(Native Method) at sun/reflect/NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) at sun/reflect/DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) at java/lang/reflect/Constructor.newInstance(Constructor.java:513) at org/apache/mina/core/service/SimpleIoProcessorPool.<init>(SimpleIoProcessorPool.java:180) at org/apache/mina/core/service/SimpleIoProcessorPool.<init>(SimpleIoProcessorPool.java:112) at org/apache/mina/core/polling/AbstractPollingIoAcceptor.<init>(AbstractPollingIoAcceptor.java:112) at org/apache/mina/transport/socket/nio/NioSocketAcceptor.<init>(NioSocketAcceptor.java:61) at iosession/MinaTimeServer.main(MinaTimeServer.java:12) at jrockit/vm/RNI.c2java(IIIII)V(Native Method) -- end of trace Memory usage report: Total mapped 1182996KB (reserved=1035732KB) - Java heap 1048576KB (reserved=983040KB) - GC tables 49784KB - Thread stacks 7936KB (#threads=13) - Compiled code 704KB (used=538KB) - Internal 648KB - OS 26800KB - Other 43684KB - Java class data 3840KB (malloced=3823KB #4815 in 858 classes) Not tracing sites. - Native memory tracking 1024KB (malloced=154KB #8) Not tracing sites. Set the env variable TRACE_ALLOC_SITES=1 or use the print_memusage switch trace_alloc_sites=true to enable alloc site tracing. ************************************************************************** * If you see this dump, please go to * * http://download.oracle.com/docs/cd/E15289_01/go2troubleshooting.html * * for troubleshooting information. * ************************************************************************** ===== END DUMP ===============================================================

invalid type code: AC 很奇怪

最近在学习网络通信。然后弄一个服务器端不断监听,客户端连接,然后也处于不断监听服务端返回的消息。本来应很简单。但在客户端的监听线程里。第一次发送消息,服务器收到,并原消息返回,没问题。第二次,服务器能收到,但返回,客户端没收到,并出现:invalid type code: AC 这样都异常。 在网上查了好多问题,基本就两种,一种是 ObjectInputStream 多次定义,一种是 序列化问题。但是我两种都坚持尝试,都是不行。 如下: public void run() { try { ObjectInputStream in = new ObjectInputStream(client.getInputStream()); while(true){ Object obj = in.readObject(); if(obj!=null){ String s = (String)obj; System.out.println("收到服务器消息:" + s); } } }catch(Exception ex){ System.err.ptinrln(ex); } } 最后,我怀着试一试的心理,把 ObjectInputStream in = new ObjectInputStream(client.getInputStream()); 放到 while 循环里,发现问题居然解决了。跟别人讲的问题居然相反。 这是什么原因呢?

springmvc 整合websocket 报错 404

第一: pom 配置文件: <dependency> <groupId>javax.websocket</groupId> <artifactId>javax.websocket-api</artifactId> <version>1.0</version> <scope>provided</scope><!--这个是从网上看的是为了解决jar包冲突的 --> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-websocket</artifactId> <version>4.1.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-messaging</artifactId> <version>4.1.6.RELEASE</version> </dependency> 第二步: 【注册,启动 websocket server 和 握手拦截器 】 @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { System.out.println("....注册......"); registry.addHandler(myhandler(), "/websocket").addInterceptors(myInterceptors()).setAllowedOrigins("*"); registry.addHandler(myhandler(), "/sockjs/websocket").addInterceptors(myInterceptors()).withSockJS(); } @Bean public WebSocketHandler myhandler() { System.out.println("....服务端......"); return new WebsocketEndPoint(); } @Bean public HandshakeInterceptor myInterceptors() { System.out.println("....握手拦截器......"); return new HandshakeInterceptor(); } } public class WebsocketEndPoint extends TextWebSocketHandler { private Logger logger = LoggerFactory.getLogger(WebsocketEndPoint.class); @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { super.handleTextMessage(session, message); logger.debug("GOMA === > WebSocketEndPoint.handlerTextMessage..."); TextMessage returnMessage = new TextMessage(message.getPayload()+" received at server"); session.sendMessage(returnMessage); } } public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor { private Logger logger = Logger.getLogger(getClass()); @Override public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception { logger.debug("GOMA ===> Before Handshake"); return super.beforeHandshake(request, response, wsHandler, attributes); } @Override public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception ex) { logger.debug("GOMA ===> After Handshake"); super.afterHandshake(request, response, wsHandler, ex); } } 第三步:页面 client 我的tomcat 的端口是 9018 socket = new WebSocket('ws://localhost:9018/testSocket/websocket'); 运行报错: WebSocket connection to 'ws://localhost:9018/testSocket/websocket' failed: Error during WebSocket handshake: Unexpected response code: 400 这是为啥? 都配置了 ,为啥 是404 奇怪~~~ 那个大神给我解决一下

数据库方言 when no Connection available

今天启动tomcat时报错了,'hibernate.dialect' must be set when no Connection available,这个错误没有连接的时候需要数据库方言,感觉可奇怪,在单位的电脑没问题,放在家里就错了,前几天没问题,今天就错了 2015-2-24 12:56:28 org.apache.catalina.core.AprLifecycleListener init 信息: The Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: E:\Common\binary\com.sun.java.jdk.win32.x86_1.6.0.013\bin;E:\Common\plugins\com.genuitec.eclipse.easie.tomcat.myeclipse_8.5.0.me201003121946\tomcat\bin 2015-2-24 12:56:28 org.apache.coyote.http11.Http11Protocol init 信息: Initializing Coyote HTTP/1.1 on http-8080 2015-2-24 12:56:28 org.apache.catalina.startup.Catalina load 信息: Initialization processed in 346 ms 2015-2-24 12:56:28 org.apache.catalina.core.StandardService start 信息: Starting service Catalina 2015-2-24 12:56:28 org.apache.catalina.core.StandardEngine start 信息: Starting Servlet Engine: Apache Tomcat/6.0.13 2015-2-24 12:56:29 org.apache.catalina.core.ApplicationContext log 信息: Initializing Spring root WebApplicationContext log4j:WARN No appenders could be found for logger (org.springframework.web.context.ContextLoader). log4j:WARN Please initialize the log4j system properly. log4j:WARN No appenders could be found for logger (org.springframework.core.CollectionFactory). log4j:WARN Please initialize the log4j system properly. 2015-2-24 12:56:32 org.apache.catalina.core.ApplicationContext log 信息: Initializing Spring root WebApplicationContext 2015-2-24 12:57:03 org.apache.catalina.core.StandardContext listenerStart 严重: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener _org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [beans.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: 'hibernate.dialect' must be set when no Connection available_ at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1337) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:221) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:423) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:729) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:381) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45) at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3827) at org.apache.catalina.core.StandardContext.start(StandardContext.java:4334) at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791) at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771) at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525) at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:920) at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:883) at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:492) at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138) at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311) at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053) at org.apache.catalina.core.StandardHost.start(StandardHost.java:719) at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045) at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443) at org.apache.catalina.core.StandardService.start(StandardService.java:516) at org.apache.catalina.core.StandardServer.start(StandardServer.java:710) at org.apache.catalina.startup.Catalina.start(Catalina.java:566) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) at java.lang.reflect.Method.invoke(Method.java:597) at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288) at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413) _Caused by: org.hibernate.HibernateException: 'hibernate.dialect' must be set when no Connection available_ at org.hibernate.dialect.resolver.DialectFactory.buildDialect(DialectFactory.java:107) at org.hibernate.cfg.SettingsFactory.buildSettings(SettingsFactory.java:138) at org.hibernate.cfg.Configuration.buildSettingsInternal(Configuration.java:2163) at org.hibernate.cfg.Configuration.buildSettings(Configuration.java:2159) at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1383) at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newSessionFactory(LocalSessionFactoryBean.java:814) at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:732) at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1368) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1334) ... 39 more 2015-2-24 12:57:03 org.apache.catalina.core.StandardContext start 严重: Error listenerStart 2015-2-24 12:57:03 org.apache.catalina.core.StandardContext start 严重: Context [/Test20150223] startup failed due to previous errors 2015-2-24 12:57:03 org.apache.catalina.core.ApplicationContext log 信息: Closing Spring root WebApplicationContext log4j:ERROR LogMananger.repositorySelector was null likely due to error in class reloading, using NOPLoggerRepository. 2015-2-24 12:57:03 org.apache.coyote.http11.Http11Protocol start 信息: Starting Coyote HTTP/1.1 on http-8080 2015-2-24 12:57:03 org.apache.jk.common.ChannelSocket init 信息: JK: ajp13 listening on /0.0.0.0:8009 2015-2-24 12:57:03 org.apache.jk.server.JkMain start 信息: Jk running ID=0 time=0/16 config=null 2015-2-24 12:57:03 org.apache.catalina.startup.Catalina start 信息: Server startup in 34874 ms

2019 Python开发者日-培训

2019 Python开发者日-培训

150讲轻松搞定Python网络爬虫

150讲轻松搞定Python网络爬虫

设计模式(JAVA语言实现)--20种设计模式附带源码

设计模式(JAVA语言实现)--20种设计模式附带源码

YOLOv3目标检测实战:训练自己的数据集

YOLOv3目标检测实战:训练自己的数据集

java后台+微信小程序 实现完整的点餐系统

java后台+微信小程序 实现完整的点餐系统

三个项目玩转深度学习(附1G源码)

三个项目玩转深度学习(附1G源码)

初级玩转Linux+Ubuntu(嵌入式开发基础课程)

初级玩转Linux+Ubuntu(嵌入式开发基础课程)

2019 AI开发者大会

2019 AI开发者大会

玩转Linux:常用命令实例指南

玩转Linux:常用命令实例指南

一学即懂的计算机视觉(第一季)

一学即懂的计算机视觉(第一季)

4小时玩转微信小程序——基础入门与微信支付实战

4小时玩转微信小程序——基础入门与微信支付实战

Git 实用技巧

Git 实用技巧

Python数据清洗实战入门

Python数据清洗实战入门

使用TensorFlow+keras快速构建图像分类模型

使用TensorFlow+keras快速构建图像分类模型

实用主义学Python(小白也容易上手的Python实用案例)

实用主义学Python(小白也容易上手的Python实用案例)

程序员的算法通关课:知己知彼(第一季)

程序员的算法通关课:知己知彼(第一季)

MySQL数据库从入门到实战应用

MySQL数据库从入门到实战应用

机器学习初学者必会的案例精讲

机器学习初学者必会的案例精讲

手把手实现Java图书管理系统(附源码)

手把手实现Java图书管理系统(附源码)

极简JAVA学习营第四期(报名以后加助教微信:eduxy-1)

极简JAVA学习营第四期(报名以后加助教微信:eduxy-1)

.net core快速开发框架

.net core快速开发框架

玩转Python-Python3基础入门

玩转Python-Python3基础入门

Python数据挖掘简易入门

Python数据挖掘简易入门

微信公众平台开发入门

微信公众平台开发入门

程序员的兼职技能课

程序员的兼职技能课

Windows版YOLOv4目标检测实战:训练自己的数据集

Windows版YOLOv4目标检测实战:训练自己的数据集

HoloLens2开发入门教程

HoloLens2开发入门教程

微信小程序开发实战

微信小程序开发实战

Java8零基础入门视频教程

Java8零基础入门视频教程

相关热词 c#跨线程停止timer c#批量写入sql数据库 c# 自动安装浏览器 c#语言基础考试题 c# 偏移量打印是什么 c# 绘制曲线图 c#框体中的退出函数 c# 按钮透明背景 c# idl 混编出错 c#在位置0处没有任何行
立即提问