android蓝牙Socket.connect失败,socket might be closed

代码如下,测试发现toast直到“mmsocket成功”都是有的,mmSocket.connect(); 那失败了,抛出“连接服务端异常2”
protected void onResume() {

         if(BluetoothMsg.isOpen)  
            {  
                Toast.makeText(mContext, "连接已经打开,可以通信。如果要再建立连接,请先断开!", Toast.LENGTH_SHORT).show();  
                return;  
            }  

// 如果点选了远程设备去连接,则本机是客户端, 开启客户端线程,接收输入流数据
if(BluetoothMsg.serviceOrCilent==BluetoothMsg.ServerOrCilent.CLIENT)

{

String address = BluetoothMsg.BlueToothAddress; //将在UI界面选中连接的蓝牙地址赋给address
if(!address.equals("null")) //如果蓝牙地址不为空
{

//在mainactivity中的get到的本地蓝牙适配器实例化成了blueadapter,在这个activity中在开头实例化成了 mBluetoothAdapter,但是它们是同一个

                    device = mBluetoothAdapter.getRemoteDevice(address);//根据蓝牙地址获取远程蓝牙设备    

// mBluetoothAdapter.cancelDiscovery();
if (device != null) {
Toast.makeText(mContext, "device成功 !", Toast.LENGTH_SHORT).show();
}
clientConnectThread = new clientThread(device); //新建并启动一个客户端线程
clientConnectThread.start();

BluetoothMsg.isOpen = true; //将BluetoothMsg类里的isOpen常量改为true
}

else

{

Toast.makeText(mContext, "蓝牙地址为空 !", Toast.LENGTH_SHORT).show();

}

}

// 如果本机是服务器,开启服务端线程,也接收输入流数据
else if(BluetoothMsg.serviceOrCilent==BluetoothMsg.ServerOrCilent.SERVICE)

{

            }  
        super.onResume();  
    }  



        //2开启客户端  读取数据            
        private class  clientThread extends Thread 
        {  
            private final BluetoothSocket mmSocket;  

            public clientThread(BluetoothDevice device) 
            {  

                BluetoothSocket tmp = null;  

                try 
                {  
                    tmp = device.createRfcommSocketToServiceRecord(UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"));  
                } catch (IOException e) {  
                    Log.e("connect", "", e);  
                    Message msg = new Message();  
                    msg.obj = "连接服务端异常1!断开连接重新试一试。";  
                    msg.what = 0;  
                    LinkDetectedHandler.sendMessage(msg);  
                }  
                mmSocket = tmp; 
                if (mmSocket!= null){
                    Toast.makeText(mContext, "mmSocket成功", Toast.LENGTH_SHORT).show();
                }
            }  

            public void run() { 
                mBluetoothAdapter.cancelDiscovery();

                try {  

                    mmSocket.connect(); 



                } catch (IOException e) {  

                    Log.e("connect", "", e);  
                    Message msg = new Message();  
                    msg.obj = "连接服务端异常2!断开连接重新试一试。";  
                    msg.what = 0;  
                    LinkDetectedHandler.sendMessage(msg);
                    return;  
                }  

            }  


        }  

1个回答

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
为什么蓝牙总是连接不上提示read failed, socket might closed or timeout, read ret: -1
自己写用服务 端与客户端,UUID使用的是rnpublic static final String BT_UUID = "00001101-0000-1000-8000-00805F9B34FB";rn服务端客户端同一个UUID 但是在BluetoothSocket connect()总是跑到异常rnread failed, socket might closed or timeout, read ret: -1rnrn别外奇怪的这个UUID服务端开户后,客户端扫描使用getuuids()[0].tostring()获的取UUID与使用的不同rn00001101a-0000-1000-8000-00805F9B34FBrn多了一个A,使用客记端故意加个A去连接还是同样的错误,附上服务端客户端代码rnrn[code=java]//服务端线程代码rn public class AcceptThread extends Threadrn private BluetoothServerSocket mServerSocket;rn private BluetoothSocket mSocket;rn private InputStream btIs;rn private OutputStream btOs;rn private PrintWriter writer;rn private boolean canAccept;rn private boolean canRev;rnrn public AcceptThread()rn canAccept = true;rn canRev = true;rn rn @Overridern public void run()rn try rnrn //获取套接字rn BluetoothServerSocket temp = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord("TEST", UUID.fromString(BT_UUID));rn mServerSocket = temp;rn //监听连接请求 -- 作为测试,只允许连接一个设备rn if(mServerSocket != null)rn mSocket = mServerSocket.accept();//阻塞等待连接rn AddShow("有客户端连接");rn rn //获取输出输入流rn btIs = mSocket.getInputStream();rn btOs = mSocket.getOutputStream();rn //通讯-接收消息rn BufferedReader reader = new BufferedReader(new InputStreamReader(btIs, "UTF-8"));rn String revTxt = null;rn if(canRev)rn revTxt = reader.readLine();rn AddShow("接收消息:" + revTxt);rn rn catch (IOException e) rn e.printStackTrace();rn finally rn try rn if(mSocket != null)rn mSocket.close();rn rn catch (IOException e)rn e.printStackTrace();rn AddShow("错误消息:" + e.getMessage());rn rn rn [/code]rnrnrn客户端 rn[code=java]rn//客户端线程rn class ConnectThread extends Thread rn private BluetoothDevice mDevice;rn private BluetoothSocket mSocket;rn private InputStream btIs;rn private OutputStream btOs;rn private boolean canRev;rn private PrintWriter writer;rnrn public ConnectThread(BluetoothDevice device) rn mDevice = device;rn canRev = true;rn rnrn @Overridern public void run() rn if (mDevice != null) rn try rn //获取套接字rn BluetoothSocket tmp = mDevice.createInsecureRfcommSocketToServiceRecord(UUID.fromString("00001101A-0000-1000-8000-00805F9B34FB"));rn mSocket = tmp;rnrn// Method m = mDevice.getClass().getMethod("createRfcommSocket", new Class[] int.class);rn// mSocket = (BluetoothSocket) m.invoke(mDevice, 1);rnrn //发起连接请求rn if (mSocket != null) rn mSocket.connect();rn rn AddShow("连接 " + mDevice.getName() + "成功!");rn //获取输入输出流rn btIs = mSocket.getInputStream();rn btOs = mSocket.getOutputStream();rn //通讯-接收消息rn BufferedReader reader = new BufferedReader(new InputStreamReader(btIs, "UTF-8"));rn String content = null;rn while (canRev) rn content = reader.readLine();rn AddShow("收到消息:" + content);rn rn catch (IOException e) rn e.printStackTrace();rn String log = e.getMessage().toString();rn AddShow("错误:" + log);rn finally rn try rn if (mSocket != null) rn mSocket.close();rn rn //btIs.close();//两个输出流都依赖socket,关闭socket即可rn //btOs.close();rn catch (IOException e) rn e.printStackTrace();rn AddShow("错误:" + e.getMessage());rn rn rn rn rnrn public void write(String msg) rn if (btOs != null) rn try rn if (writer == null) rn writer = new PrintWriter(new OutputStreamWriter(btOs, "UTF-8"), true);rn rn writer.println(msg);rn catch (UnsupportedEncodingException e) rn e.printStackTrace();rn writer.close();rn AddShow("错误:" + e.getMessage());rn rn rn rn rn[/code]rnrnrn连接的代码rn[code=java]rnif(device.getName() != null) rnrn AddShow("找到设备" + device.getName());rn if(device.getUuids() != null)rn AddShow(device.getUuids()[0].toString());rn rn if(device.getName().equals(m_blueName))rn rn m_device = device;rn Toast.makeText(MainActivity.this, "找到设备", Toast.LENGTH_SHORT).show();rn stopDiscovery();rn mConnectThread = new ConnectThread(device);rn mConnectThread.start();rn rn //m_devicelist.add(device);rn rn[/code]
socket closed??
写了一个传文件的程序,我在服务器端搞了个按钮,里面的事件就是关闭服务(也就是关闭端口),rn但按下去后抛异常?rnjava.net.SocketException: socket closedrnjava.net.SocketException: socket closedrn at java.net.PlainSocketImpl.socketAccept(Native Method)rn at java.net.PlainSocketImpl.accept(PlainSocketImpl.java:384)rn at java.net.ServerSocket.implAccept(ServerSocket.java:450)rn at java.net.ServerSocket.accept(ServerSocket.java:421)rn at itsys.yr.ServerStart.startServer(ServerStart.java:41)rn at itsys.yr.ServerTest.run(ServerTest.java:84)rn at java.lang.Thread.run(Thread.java:595)rn
socket closed
会造成socket closed 的原因有哪些?
socket is closed
package Server.model;rnrnimport i.qq.common.Message;rnrnimport java.io.IOException;rnimport java.io.ObjectInputStream;rnimport java.net.Socket;rnrnpublic class qqServerThread extends Threadrn Socket s=null;rn rnpublic qqServerThread(Socket s) rn this.s=s;// TODO 自动生成的构造函数存根rn rnrnpublic void run()rn while(true)rn try rn ObjectInputStream ois=new ObjectInputStream(s.getInputStream());rn Message ms=(Message)ois.readObject();rn System.out.print(ms.getId()+"对"+ms.getSender()+"说:"+ms.getInformation());rn catch (IOException e) rn // TODO 自动生成的 catch 块rn e.printStackTrace();rn catch (ClassNotFoundException e) rn // TODO 自动生成的 catch 块rn e.printStackTrace();rn rn rn rnrnrn服务器rnrnpackage Server.model;rnrnimport i.qq.common.Message;rnimport i.qq.common.User;rnrnimport java.io.IOException;rnimport java.io.ObjectInputStream;rnimport java.io.ObjectOutputStream;rnimport java.net.ServerSocket;rnimport java.net.Socket;rnimport java.security.interfaces.RSAKey;rnimport java.sql.ResultSet;rnimport java.sql.SQLException;rnrnimport qq.server.DB.qqServerSqlHelp;rnrnpublic class Serverqq rn qqServerSqlHelp qqss=null;rn public Serverqq() rn System.out.print("服务器在9999端口监听");rn try rn ServerSocket ss = new ServerSocket(9999);rn while (true) rn Socket s = ss.accept();rn ObjectInputStream ois = new ObjectInputStream(rn s.getInputStream());rn User u = (User) ois.readObject();rn Message ms = new Message();rn String sql = "select 用户名 from Denlu where 用户名=? and 密码=?";rn String pasa[] = u.getUs(), u.getPw() ;rn qqss = new qqServerSqlHelp();rn ResultSet rs = qqss.Query(sql, pasa);rn ObjectOutputStream oos = new ObjectOutputStream(rn s.getOutputStream());rn if (rs.next()) rn rs.getString(1);rn ms.setMessType("1");rn rn //一对一单开一个线程rn qqServerThread qqst=new qqServerThread(s);rn qqst.start();rn else rn ms.setMessType("2"); rn rn oos.writeObject(ms);rn s.close();rn rn catch (IOException e) rn // TODO 自动生成的 catch 块rn e.printStackTrace();rn catch (ClassNotFoundException e) rn // TODO 自动生成的 catch 块rn e.printStackTrace();rn catch (SQLException e) rn // TODO 自动生成的 catch 块rn e.printStackTrace();rn finallyrn qqss.close();rn rn rnrnrn
Socket.Connect
[code=C#] IPEndPoint srvInfo = new IPEndPoint(GetSrvIp(), 8888);rn cliSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);rn tryrn rn cliSocket.Connect(srvInfo);[/code]rnrnrn那个cliSocket.Connect().如何输入错误的ip,他会卡在那,怎么能有个时间限制或什么的》》???rnrnrn[code=C#] TCPConnection conn = new TCPConnection(_ipAddr, port);rn TcpClient _tcpc = conn.Connect();rn if (_tcpc == null)rn rn MessageBox.Show("无法连接到服务器,请重试!",rn "rn [/code]
android socket创建失败
实现功能:点击按键,向某个网址的某个端口,发送数据[code=java] class textDisitListener implements OnClickListenerrn rn public void onClick(View v) rn rn new textDisThread().start();rn rn rn class textDisThread extends Threadrn rn public void run()rn rn String str11 = new String("asdfasdf");rn Log.i("socket","loading...");rn try rn Socket socketTest = new Socket(SERVERIP,SERVERPORT);rn Log.i("socket","load.");rn PrintWriter outw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socketTest.getOutputStream(),"GB2312")),true);rn outw.println(str11);rn Log.i("TextSend","textsend");rn outw.flush();rn outw.close();rn socketTest.close();rn catch (UnknownHostException e) rn // TODO 自动生成的 catch 块rn e.printStackTrace();rn catch (IOException e) rn // TODO 自动生成的 catch 块rn e.printStackTrace();rn rn rn [/code]rn在adb上运行没有问题,但是到了手机上调试时候发现Socket socketTest = new Socket(SERVERIP,SERVERPORT);这一行根本就过不去。rnrn后来做了测试。[code=java] class btnListener implements OnClickListenerrn rn public void onClick(View v) rn rn new textDisThread().start();rn rn rn class textDisThread extends Thread rn rn Socket socket1 = new Socket(SERVERIP,SERVERPORT);rn [/code]rn只有新建,什么都不做,一样报错。rn缺省构造函数不能处理隐式超构造函数抛出的异常类型 IOException。必须定义显式构造函数。rn这个怎么处理呢?
java.net.SocketException: Socket closed 错误
public String httpPostNameValuePair(String url,Map URLParams)rn rn String returnString=null;rn DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);rn httpClient.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS,true);rnrn List nvps=httpClientGetURLParams(URLParams);rn HttpPost httpPost=newNameValuePairHttpPost(url, nvps);rn HttpResponse response=httpClientExecute(httpClient,httpPost);//response.getFirstHeader("Location").getValue();rnrn //if(response.getStatusLine().getStatusCode()==HttpStatus.SC_OK)//判断是否正确执行(如果网页执行程序出问题,会返回500)rn rn tryrn rn returnString=EntityUtils.toString(response.getEntity());//InputStream is=response.getEntity().getContent();rn rn catch (IOException e)rn rn e.printStackTrace();rn rn rn httpClient.getConnectionManager().shutdown();rn return returnString;rn rnrnrn麻烦看上面函数,一直都运行好好的,怎么今天发现抛出下面错误: 麻烦看下,谢谢。rn07-09 17:20:57.476 6275-6502/com.logohoo.manstore.app W/System.err﹕ java.net.SocketException: Socket closedrn07-09 17:20:57.486 6275-6502/com.logohoo.manstore.app W/System.err﹕ at libcore.io.Posix.recvfromBytes(Native Method)rn07-09 17:20:57.486 6275-6502/com.logohoo.manstore.app W/System.err﹕ at libcore.io.Posix.recvfrom(Posix.java:131)rn07-09 17:20:57.496 6275-6502/com.logohoo.manstore.app W/System.err﹕ at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:164)rn07-09 17:20:57.496 6275-6502/com.logohoo.manstore.app W/System.err﹕ at libcore.io.IoBridge.recvfrom(IoBridge.java:513)rn07-09 17:20:57.496 6275-6502/com.logohoo.manstore.app W/System.err﹕ at java.net.PlainSocketImpl.read(PlainSocketImpl.java:489)rn07-09 17:20:57.496 6275-6502/com.logohoo.manstore.app W/System.err﹕ at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)rn07-09 17:20:57.506 6275-6502/com.logohoo.manstore.app W/System.err﹕ at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:241)rn07-09 17:20:57.506 6275-6502/com.logohoo.manstore.app W/System.err﹕ at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103)rn07-09 17:20:57.506 6275-6275/com.logohoo.manstore.app I/Choreographer﹕ Skipped 796 frames! The application may be doing too much work on its main thread.rn07-09 17:20:57.516 6275-6502/com.logohoo.manstore.app W/System.err﹕ at org.apache.http.impl.io.AbstractSessionInputBuffer.read(AbstractSessionInputBuffer.java:134)rn07-09 17:20:57.516 6275-6502/com.logohoo.manstore.app W/System.err﹕ at org.apache.http.impl.io.ContentLengthInputStream.read(ContentLengthInputStream.java:174)rn07-09 17:20:57.516 6275-6502/com.logohoo.manstore.app W/System.err﹕ at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:159)rn07-09 17:20:57.516 6275-6502/com.logohoo.manstore.app W/System.err﹕ at java.io.InputStreamReader.read(InputStreamReader.java:244)rn07-09 17:20:57.526 6275-6502/com.logohoo.manstore.app W/System.err﹕ at java.io.Reader.read(Reader.java:145)rn07-09 17:20:57.526 6275-6502/com.logohoo.manstore.app W/System.err﹕ at org.apache.http.util.EntityUtils.toString(EntityUtils.java:135)rn07-09 17:20:57.526 6275-6502/com.logohoo.manstore.app W/System.err﹕ at org.apache.http.util.EntityUtils.toString(EntityUtils.java:146)
关于java.net.SocketException: Socket closed
下面这段代码的------> out.write(buf, 0, len)报异常rnjava.net.SocketException: Socket closedrn at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:99)rn at java.net.SocketOutputStream.write(SocketOutputStream.java:136)rn at weblogic.servlet.internal.ChunkOutput.writeChunkNoTransfer(ChunkOutput.java:548)rn at weblogic.servlet.internal.ChunkOutput.writeChunks(ChunkOutput.java:505)rn at weblogic.servlet.internal.ChunkOutput.flush(ChunkOutput.java:382)rn at weblogic.servlet.internal.ChunkOutput.checkForFlush(ChunkOutput.java:469)rn at weblogic.servlet.internal.ChunkOutput.write(ChunkOutput.java:304)rn at weblogic.servlet.internal.ChunkOutputWrapper.write(ChunkOutputWrapper.java:137)rn at weblogic.servlet.internal.ServletOutputStreamImpl.write(ServletOutputStreamImpl.java:168)rn at jp.co.nes.necle.common.util.ServletUtils.download(ServletUtils.java:126)rn at jp.co.nes.necle.common.util.ServletUtils.download(ServletUtils.java:97)rn at jp.co.nes.necle.goods.web.PublishingOutPutCSVAllAction.showPublishingOutPutCSVAll(PublishingOutPutCSVAllAction.java:535)rn at jp.co.nes.necle.goods.web.PublishingOutPutCSVAllAction.perform(PublishingOutPutCSVAllAction.java:83)rn at org.apache.struts.action.ActionServlet.processActionPerform(ActionServlet.java:1787)rn at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1586)rn at jp.co.nes.necle.common.web.BasicActionServlet.process(BasicActionServlet.java:87)rn at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:510)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)rn at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:226)rn at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:124)rn at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:283)rn at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:175)rn at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3370)rn at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)rn at weblogic.security.service.SecurityManager.runAs(Unknown Source)rn at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2117)rn at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2023)rn at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1359)rn at weblogic.work.ExecuteThread.execute(ExecuteThread.java:200)rn at weblogic.work.ExecuteThread.run(ExecuteThread.java:172)rnjava.net.SocketException: Socket closedrn at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:99)rn at java.net.SocketOutputStream.write(SocketOutputStream.java:136)rn at weblogic.servlet.internal.ChunkOutput.writeChunkNoTransfer(ChunkOutput.java:548)rn at weblogic.servlet.internal.ChunkOutput.writeChunks(ChunkOutput.java:505)rn at weblogic.servlet.internal.ChunkOutput.flush(ChunkOutput.java:382)rn at weblogic.servlet.internal.ChunkOutput.checkForFlush(ChunkOutput.java:469)rn at weblogic.servlet.internal.ChunkOutput.write(ChunkOutput.java:304)rn at weblogic.servlet.internal.ChunkOutputWrapper.write(ChunkOutputWrapper.java:137)rn at weblogic.servlet.internal.ServletOutputStreamImpl.write(ServletOutputStreamImpl.java:168)rn at jp.co.nes.necle.common.util.ServletUtils.download(ServletUtils.java:126)rn at jp.co.nes.necle.common.util.ServletUtils.download(ServletUtils.java:97)rn at jp.co.nes.necle.goods.web.PublishingOutPutCSVAllAction.showPublishingOutPutCSVAll(PublishingOutPutCSVAllAction.java:535)rn at jp.co.nes.necle.goods.web.PublishingOutPutCSVAllAction.perform(PublishingOutPutCSVAllAction.java:83)rn at org.apache.struts.action.ActionServlet.processActionPerform(ActionServlet.java:1787)rn at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1586)rn at jp.co.nes.necle.common.web.BasicActionServlet.process(BasicActionServlet.java:87)rn at org.apache.struts.action.ActionServlet.doPost(ActionServlet.java:510)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)rn at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)rn at weblogic.servlet.internal.StubSecurityHelper$ServletServiceAction.run(StubSecurityHelper.java:226)rn at weblogic.servlet.internal.StubSecurityHelper.invokeServlet(StubSecurityHelper.java:124)rn at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:283)rn at weblogic.servlet.internal.ServletStubImpl.execute(ServletStubImpl.java:175)rn at weblogic.servlet.internal.WebAppServletContext$ServletInvocationAction.run(WebAppServletContext.java:3370)rn at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:321)rn at weblogic.security.service.SecurityManager.runAs(Unknown Source)rn at weblogic.servlet.internal.WebAppServletContext.securedExecute(WebAppServletContext.java:2117)rn at weblogic.servlet.internal.WebAppServletContext.execute(WebAppServletContext.java:2023)rn at weblogic.servlet.internal.ServletRequestImpl.run(ServletRequestImpl.java:1359)rn at weblogic.work.ExecuteThread.execute(ExecuteThread.java:200)rn at weblogic.work.ExecuteThread.run(ExecuteThread.java:172)rn不知道什么原因,希望各位高手解答rn代码:rn private static void download(HttpServletResponse response,rn InputStream in, int contentLength, String fileName)rn throws IOException rn response.reset();rn response.setContentLength(contentLength);rn response.setContentType("application/octet-stream");rn response.setHeader("Content-Disposition",rn "attachment; filename=\"" + fileName + "\"");rn OutputStream out = null;rn try rn out = response.getOutputStream();rn byte[] buf = new byte[512];rn int len;rn while ((len = in.read(buf)) != -1) rn ------> out.write(buf, 0, len);rn rn catch (Exception e) rn e.printStackTrace();rn finally rn try rn in.close();rn catch (IOException e) rn e.printStackTrace();rn rn if (out != null) rn try rn out.close();rn catch (IOException e) rn e.printStackTrace();rn rn rn rn
急!Socket is closed的问题
我写了一个C/S模式的程序,客户端可以发给服务器一些字符串,服务器也接收的到,但是当服务器再向客户端发回去的时候rn就会出现java.net.SocketException: Socket is closed rn请问到底是怎么回事?
java.net.SocketException: socket closed
rnjava.net.SocketException: socket closedrn at java.net.SocketInputStream.socketRead0(Native Method)rn at java.net.SocketInputStream.read(Unknown Source)rn at java.net.SocketInputStream.read(Unknown Source)rn at java.io.DataInputStream.readInt(Unknown Source)rn at cn.xxx.clientsimulate.client.Client.receiveData(Client.java:339)rn at cn.xxx.clientsimulate.client.ReceiveDataThread.run(ReceiveDataThread.java:60)rnrn做压力测试的时候的异常抛出.程序本身应该问题不大.rnrn阻塞式写的 DataInputStream.readInt() 作为自定义报文的 包长.rnrn但在运行个十多分钟之后 频繁出现 这个 SocketException. 并且说我 readInt 的时候异常.rnrn我想, 要么是服务器主动给我踢了. 是这样的话应该报java.net.SocketException: Connection reset 才对.rn再或者报: 远程主机强迫断开一个什么什么什么什么之类的.rnrn他这个readInt的时候 报这个是什么情况呢
android studio 蓝牙 socket 范例
这是很简洁的android 蓝牙和socket的范例,开发环境为android studio
java.net.SocketException: Socket closed
现在有一个android项目用到了google Map,本地网络经常刷新不出来地图,所以我把手机翻墙了,google,facebook都能打开。rn但是和我自己的服务器不能连接上了,我的想法是我的服务器端已经发布了,就算翻墙应该也是能访问的,只是慢了点而已,但是现在抛出了一个异常,java.net.SocketException: Socket closedrnrn HttpPost postMethod = new HttpPost(baseUrl); rn postMethod.setEntity(new UrlEncodedFormEntity(params, "utf-8")); //将参数填入POST Entity中 rn HttpClient httpClient = new DefaultHttpClient();rn httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 6000);rn httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 3000);rn[color=#FF0000] HttpResponse response = httpClient.execute(postMethod); [/color]rnrnrn红色部分为抛异常部分,求大神给分析一下。
Socket蓝牙
使用蓝牙需要的权限: //允许程序连接到已配对的蓝牙设备//允许程序发现和配对蓝牙设备   蓝牙模块的串口(规定好的) String SPP_UUID = "00001101-0000-1000-8000-00805F9B34FB";//蓝牙开关// 初始化本机蓝牙功能BluetoothAdapter  btAdapter = BluetoothAdapter.getDefaultAdapter(
关于蓝牙连接的问题read failed, socket might closed or timeout, read ret: -1
出现read failed, socket might closed or timeout, read ret: -1 是什么原因呀rnUUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");rnrnsocket = device.createRfcommSocketToServiceRecord(MY_UUID);rnrnsocket.connect()[img=https://forum.csdn.net/PointForum/ui/scripts/csdn/Plugin/003/monkey/8.gif][/img]
closed~~~closed~~~closed
closed closed~~~closed~~~closed closed~~~closed~~~closed
事务提交失败:session is closed
//事务提交的方法rnpublic static void commitTransaction() rn rn Transaction tx = (Transaction) tLocaltx.get();rn rn try rn if (tx!=null && !tx.wasCommitted() && !tx.wasRolledBack()) rn tx.commit();rn rn tLocaltx.set(null);rn catch (HibernateException e) rn System.out.println("事务提交失败:"+e.getMessage());rn rn
socket closed异常 怎么解决
package com.example.client;rnrnimport android.os.Bundle;rnimport android.os.Handler;rnimport android.os.Message;rnimport android.util.Log;rnrnimport java.io.BufferedReader;rnimport java.io.BufferedWriter;rnimport java.io.DataInputStream;rnimport java.io.DataOutputStream;rnimport java.io.IOException;rnimport java.io.InputStream;rnimport java.io.InputStreamReader;rnimport java.io.OutputStream;rnimport java.io.OutputStreamWriter;rnimport java.io.Writer;rnimport java.net.Socket;rnimport java.util.ArrayList;rnimport java.util.List;rnimport java.util.Scanner;rnrnimport android.app.Activity;rnimport android.view.Menu;rnimport android.view.View;rnimport android.widget.ArrayAdapter;rnimport android.widget.Button;rnimport android.widget.EditText;rnimport android.widget.ListView;rnimport android.widget.Toast;rnrnpublic class MainActivity extends Activity rn private Button btnConnect;rn private Button btnSend;rn private EditText etIp;rn private EditText etText;rn private ListView listView;rn private List messages = new ArrayList();rn private ArrayAdapter adapter;rn private Socket socket;rn // private DataInputStream dis;rn // private DataOutputStream dos;rnrn //主线程中创建handler对象rn private Handler handler = new Handler()rn //handler自动调用 当消息队列中有消息对象时rn //将会调用该方法 处理这个消息rn public void handleMessage(android.os.Message msg) rn //处理消息 这个方法在主线程中执行rn switch (msg.what) rn case HANDLER_MESSAGE_RECEIVED: //接收到了消息rn adapter.notifyDataSetChanged();rn //永远看到最后一条rn listView.setSelection(messages.size()-1);rn break;rn case HANDLER_CONNECT_SUCCESS: //接收到了连接成功的消息rn Toast.makeText(MainActivity.this, "恭喜!建立连接成功!", Toast.LENGTH_SHORT).show();rn etIp.setEnabled(false);rn btnConnect.setEnabled(false);rn break;rn case HANDLER_CONNECT_FAIL: //接收到了连接失败的消息rn Toast.makeText(MainActivity.this, "恭喜!建立连接失败!", Toast.LENGTH_SHORT).show();rn break;rn rn rn ;rnrn public static final int HANDLER_CONNECT_SUCCESS=0;rn public static final int HANDLER_CONNECT_FAIL=1;rn public static final int HANDLER_MESSAGE_RECEIVED=2;rnrn @Overridern protected void onCreate(Bundle savedInstanceState) rn super.onCreate(savedInstanceState);rn setContentView(R.layout.activity_main);rn //控件初始化rn setViews();rn //给listView设置适配器rn adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, messages);rn listView.setAdapter(adapter);rn rnrn /** 控件初始化 */rn private void setViews() rn btnConnect = (Button) findViewById(R.id.btnConnect);rn btnSend = (Button) findViewById(R.id.btnSend);rn listView = (ListView) findViewById(R.id.listView);rn etIp = (EditText) findViewById(R.id.etIp);rn etText = (EditText) findViewById(R.id.etText);rn rnrn public void doClick(View view)rn switch (view.getId()) rn case R.id.btnConnect: //建立连接rn connect();rn break;rn case R.id.btnSend: //发送消息rn sendMessage();rn break;rn rn rn private BufferedWriter buffWr = null;rn private BufferedReader buff;rn protected OutputStream ops;rn protected OutputStreamWriter opsw;rn protected BufferedWriter bw;rn /** 发送消息 */rn private void sendMessage() rn new Thread()rn public void run() rn try rn //把文本框中的内容获取到 发消息rn String text = etText.getText().toString();rn bw.write("梦迪:\n"+text);rn bw.flush();rn // bw.close();rn catch (IOException e) rn e.printStackTrace();rn rn rn .start();rn rnrn /** 建立网络连接 */rn private void connect() rn new Thread()rn public void run() rn try rn socket = new Socket("192.168.1.185", 7080); rn InputStream fileInputStream=socket.getInputStream();rn InputStreamReader inputStreamReader=new InputStreamReader(fileInputStream);rn BufferedReader bufferedWriter2=new BufferedReader(inputStreamReader);rn ops = socket.getOutputStream();rn opsw = new OutputStreamWriter(ops,"UTF-8");rn bw = new BufferedWriter(opsw);rn //不出异常 说明连接建立成功rn //给handler发送一个连接成功的消息rn Message msg = new Message();rn msg.what = HANDLER_CONNECT_SUCCESS; rn handler.sendMessage(msg);rn //启动子线程 用于不断读取服务端的消息rn new ReadThread().start();rn catch (IOException e) rn e.printStackTrace();rn //连接创建失败 提示用户rn handler.sendEmptyMessage(HANDLER_CONNECT_FAIL);rn rn rn .start();rn rnrn /** 专门用于读取服务端返回的消息 */rn public class ReadThread extends Threadrn public void run() rn tryrn while(buff.readLine()!=null)rn String message=buff.readLine();rn Log.i("info", "接收到了消息:"+message);rn //把消息添加到消息集合中rn messages.add(message);rn //更新ListView的适配器rn handler.sendEmptyMessage(HANDLER_MESSAGE_RECEIVED);rn rn catch(Exception e)rn e.printStackTrace();rn rn rn rnrnrnrnrn连接成功后,发消息报异常rn服务端启动rnLAPTOP-3L84R6L0:连接成功!rnLAPTOP-3L84R6L0/192.168.1.185:java.io.BufferedReader@4e25154f说rn:姊﹁开锛?rnException in thread "main" java.net.SocketException: socket closedrn at java.net.SocketInputStream.socketRead0(Native Method)rn at java.net.SocketInputStream.socketRead(Unknown Source)rn at java.net.SocketInputStream.read(Unknown Source)rn at java.net.SocketInputStream.read(Unknown Source)rn at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)rn at sun.nio.cs.StreamDecoder.implRead(Unknown Source)rn at sun.nio.cs.StreamDecoder.read(Unknown Source)rn at java.io.InputStreamReader.read(Unknown Source)rn at java.io.BufferedReader.fill(Unknown Source)rn at java.io.BufferedReader.readLine(Unknown Source)rn at java.io.BufferedReader.readLine(Unknown Source)rn at cn.tedu.Server.main(Server.java:27)rn
java连接数据库出现socket closed错误
一段java程序rn首先调用1个batrn之后在程序中连接数据rnbat文件的内容是insert操作rnsqlplus user/passwordrninsert .....rninsert .....rnrn现在是调用完bat之后,然后连接数据库,进行检索操作的时候,就出现socket closed错误rn如果不调用这个bat,直接进行数据库连接,然后检索,就没有问题rn哪位大虾知道是什么原因阿rn谢谢了先
求解Io 异常: Socket closed
我用hibernate连接数据库,在hibernate.cfg.xml文件中有映射文件的配置如下:rnrn jdbc:oracle:thin:@127.0.0.1:1521:xernrn rn org.hibernate.dialect.Oracle9Dialectrnrn rn gwaprnrn rn gwaprnrn rn oracle.jdbc.driver.OracleDriverrnrn rn truernrn rn truern rn rn updatern true 1,false 1rn 50rn truern 4rn 50rn rn rn rn rn rn rn rn rn rn rn rn rnrn我在测试程序中就写了一句:System.out.println(new Configuration().configure().buildSessionFactory());rn地一次运行是没有问题的,一旦运行之后数据库中的表就创建好了,再运行时就出现异常,当把表删除之后运行又不会有异常,当表创建好之后又会出现此异常,请高手指点,异常如下:rn2010-04-25 18:45:44,449 WARN (org.hibernate.connection.DriverManagerConnectionProvider:155) - problem closing pooled connectionrnjava.sql.SQLException: Io 异常: Socket closedrn at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:125)rn at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:162)rn at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:274)rn at oracle.jdbc.driver.T4CConnection.logoff(T4CConnection.java:393)rn at oracle.jdbc.driver.PhysicalConnection.close(PhysicalConnection.java:1036)rn at org.hibernate.connection.DriverManagerConnectionProvider.close(DriverManagerConnectionProvider.java:152)rn at org.hibernate.connection.DriverManagerConnectionProvider.finalize(DriverManagerConnectionProvider.java:142)rn at java.lang.ref.Finalizer.invokeFinalizeMethod(Native Method)rn at java.lang.ref.Finalizer.runFinalizer(Finalizer.java:83)rn at java.lang.ref.Finalizer.access$100(Finalizer.java:14)rn at java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:160)rn2010-04-25 18:45:44,463 INFO (org.hibernate.connection.DriverManagerConnectionProvider:147) - cleaning up connection pool: jdbc:oracle:thin:@127.0.0.1:1521:xern2010-04-25 18:45:44,464 WARN (org.hibernate.connection.DriverManagerConnectionProvider:155) - problem closing pooled connectionrnjava.sql.SQLException: Io 异常: Socket closed
求助:Socket.connect
服务器端代码:rn private IPEndPoint ServerInfo;rn private Socket ServerSocket;rnrn private void button_Start_Click(object sender, EventArgs e)rn rn ServerSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);rn ServerInfo = new IPEndPoint(IPAddress.Any,Convert.ToInt32("6000"));rn ServerSocket.Bind(ServerInfo);rn ServerSocket.Listen(10);rn button_Stop.Enabled = true;rn button_Start.Enabled = false;rn MessageBox.Show("启动成功");rn rnrn private void button_Stop_Click(object sender, EventArgs e)rn rn ServerSocket.Close();rn button_Start.Enabled = true;rn button_Stop.Enabled = false;rn MessageBox.Show("启动结束");rn rn客户端代码:rn private IPEndPoint ServerInfo;rn private Socket ClientSocket;rn private void button_Enter_Click(object sender, EventArgs e)rn rn ServerInfo = new IPEndPoint(IPAddress.Parse("127.0.0.1"), Convert.ToInt32("6000"));rn tryrn rn ClientSocket.Connect(ServerInfo);rn MessageBox.Show("登录服务器成功");rn rn rn catchrn rn MessageBox.Show("登录服务器失败");rn rn rn为什么连接不上????
socket为何会自己closed?
最近学习socketrn自己写了个C/Srn写好后发现rn如果我用client上传文件到serverrn第一次是成功的rn但第二次再上传的话rn报错socket closedrnrn但我全篇代码都没有调用socket.close()方法?rn这是为何?
输出流下载问题? Socket closed
项目为struts2+spring+ibatis前台为extjsrn页面有导出功能, 可将数据导到excel中, 并下载rn但遇到个问题rn如果导出的数据过多(超过1000条), 当使用ie浏览器点导出按钮后, 页面弹出下载提示(有打开、保存功能)rn此时不进行操作rn大概过1分钟左右的时间, 控制台会报出如下异常:rn[code=Java]rn<2011-11-24 上午08时50分47秒 GMT> <[weblogic.servlet.internal.WebAppServletContext@ee9368 - appName: '_appsdir_SEC_dir', name: 'SEC', context-path: '/SEC'] Root cause of ServletException.rnjava.net.SocketException: Socket closedrn at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:99)rn at java.net.SocketOutputStream.write(SocketOutputStream.java:136)rn at weblogic.servlet.internal.ChunkOutput.writeChunkTransfer(ChunkOutput.java:525)rn at weblogic.servlet.internal.ChunkOutput.writeChunks(ChunkOutput.java:504)rn at weblogic.servlet.internal.ChunkOutput.flush(ChunkOutput.java:382)rn Truncated. see log file for complete stacktracern[/code]rn出现异常后点打开后 excel会提示文件损坏 此时打开的excel文件仅有少量数据 而且excel表格内的文字样式也不对rnrn但使用firefox浏览器则没有此类问题。rnrnjava中的导出代码片段:rn[code=Java]rnthis.getResponse().setHeader("Cache-Control", "no-cache");rnthis.getResponse().setDateHeader("Expires", 0);rnthis.getResponse().setContentType("application/vnd.ms-excel;charset=UTF-8");rnthis.getResponse().setHeader("Content-Disposition", "attachment;filename=" + new String((title + ".xls").getBytes("GBK"), "iso8859-1"));rnrnWritableWorkbook workbook = Workbook.createWorkbook(this.getResponse().getOutputStream());rnrn// ......excel表格内文字边框等样式 此处省略rn// ......查数据库 遍历list往表格内写数据 此处省略rnrnworkbook.write();rnworkbook.close();rn[/code]rnrn问题不大, 可以不解决, 但想求一个真相…… 知道的朋友帮帮忙
android关于连接蓝牙socket 通道
有时候 我们需要 自动连接 app 的socket 数据通道   ,,通常情况下,我们都只是 手点 设置》蓝牙 》搜索 》绑定》连接  电话/多媒体 》   ,上面的连接 仅仅是 A2DP 以及HEADSET 的连接    如何 自动连接  socket通道?  楼主有了一个想法 代码如下: // 检查如果蓝牙音频连接。 int result = bluetoothAdapter.get
Heroes Of Might And Magic
In the new version of the famous game "Heroes of Might and Magic" heroes themselves take active part in battles. More of that, hero can defeat some monsters alone, without any supporting army. In this problem you are asked to develop the program which would find the strategy for a mage hero fighting face to face with a pack of monsters.nEach hero initially has HP_H hit points and MP_H mana points. Heroes can use different spells. Your hero knows three spells: Lighting Bolt, Teleport and Heal. Each spell costs one mana point.nnEach monster has HP_M hit points. Pack of monsters is a single group of several monsters who act as one. Therefore if initially the pack consists of N_M monsters, they have N_M x HP_M hit points. As the battle proceeds, monsters' number of hit points decreases. If monsters have H hit points, that means that the group consists of ceiling(H / HP_M) monsters (ceiling is a function that returns the smallest integer number not less its argument).nnThe battle runs on a one-dimensional battlefield consisting of N + 1 squares, numbered starting from 0. Your hero resides on the square number 0 and does not move. Monsters initially reside on Nth square and can move. Monsters can move at most V squares a turn.nnThe battle consists of turns. First your hero makes a turn, then the monsters, and so on. Monsters' strategy is very easy - they move in the direction of your hero min(V, P - 1) squares where P is the square number where they were in the beginning of their turn. If the monsters are on the square number 1 in the end of the movement, then they strike your hero. If there are K monsters left in a pack, their strike decreases hit points of the hero by K. If your hero has non-positive hit points, then the hero is defeated.nnYour hero's turn is always the casting of some spell. Lighting Bolt spell removes LP hit points from a pack of monsters, where P is the square number on which the monsters reside. Teleport spell moves monsters to any desired square (except 0 where your hero resides). Heal spell adds dH hit points to hero. However, his hit points never exceed HP_H, so if after using Heal spell his hit points are greater then HP_H, they are decreased to HP_H. If your hero has zero mana points and there is at least one monster left in the pack, then the hero is defeated.nnFind the strategy which would allow your hero to defeat monsters. Monsters are defeated if their hit points are non-positive.nnnInputnnThe first line of the input file contains positive integer numbers separated by spaces in the following order: N, HP_H, MP_H, HP_M, N_M, V, dH. (1 <= N <= 10, 2 <= HP_H <= 100, 1 <= MP_H <= 50, 1 <= HP_M <= 10, 1 <= N_M <= 10, 1 <= V <= N, 1 <= dH < HP_H). The second line of the input file contains N integer numbers L1, L2, ..., LN (1 <= LP <= 10), separated by spaces.nnProcess to the end of file.nnnOutputnnIf the hero cannot win the battle, write the word DEFEATED on the first line of the output file. In the other case write the word VICTORIOUS on the first line of the output file and then write any sequence of hero's actions that leads to victory, where each line of the output file starting from the second one must correspond to one hero's turn. The first character of the line must be one of the following:nnL - Cast Lighting Bolt spell. nT - Cast Teleport spell. nH - Cast Heal spell. nIf the hero casts Teleport spell then T character must be followed by a space and an integer number from 1 to N - the square number where the monsters should be teleported to.nnnSample Inputnn2 3 2 1 2 1 1n1 1n2 3 2 3 1 1 1n1 1n4 4 3 1 4 1 1n3 1 1 1n1 6 5 1 4 1 3n1nnnSample OutputnnVICTORIOUSnLnLnDEFEATEDnVICTORIOUSnLnT 2nLnVICTORIOUSnLnLnHnLnL
蓝牙enable 失败问题
上电蓝牙芯片默认的波特率为115200,但是实际上蓝牙在正常工作的时候115200波特率满足不了通信速度,需要提升波特率。 曾经遇到过一款蓝牙芯片有一款没有CTS 管脚,但是在CPU这边已经配置启用了硬件流校验功能,导致蓝牙使能失败。 查看蓝牙log发现在115200时候CPU与蓝牙通信正常,提高波特率开始硬件流校验功能后一直等待不到蓝牙芯片反馈的数据导致使能失败,最后才知道蓝牙芯片没有CTS...
蓝牙3.0 socket 通信
请各位大神指教,蓝牙模块2.0 通过 socket 方式能够正常连接下位机,为什么蓝牙模块3.0 通过socket 方式不能够正常连接下位机,请大神指教,谢谢!
关于蓝牙socket的问题
socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM)总是失败,我查了些资料,大概问题是缺少xp sp2 蓝牙安装包,如果是这个问题的话这个包从哪里下载阿,谁有给我一份
Socket蓝牙传输
Bluetooth是目前使用最广泛的无线通讯协议,近距离无线通讯的标准。 主要针对短距离设备通讯(10米)无线耳机,无线鼠标,无线键盘
蓝牙socket的recv()问题
在Windows Mobile6.1系统上做蓝牙,使用socket。rn现在搜索、连接、发送都没有问题。接收用的是recv()堵塞,现在的情况是:能收到数据,但每次收几个字节就通知我,完整的一帧(自定义的)要分好多次才能收完。例如发送1234567890,会先收一个字节“1”,再收“234567”,再收“890”这样。rn想请教一下,是不是什么参数我没有设置?堵塞接收怎样才能一次接收成功完整的一帧?rn源码如下:[code=C/C++][/code]rnrn//rn#include rn#include rnrn#ifdef _DEBUGrn#define new DEBUG_NEWrn#endifrn#define lengthof(exp) ((sizeof((exp)))/sizeof((*(exp))))rn#define IOCTL_SERVICE_START CTL_CODE(FILE_DEVICE_SERVICE, 1, METHOD_BUFFERED, FILE_ANY_ACCESS)rn#define IOCTL_SERVICE_STOP CTL_CODE(FILE_DEVICE_SERVICE, 2, METHOD_BUFFERED, FILE_ANY_ACCESS)rn#define IOCTL_SERVICE_REFRESH CTL_CODE(FILE_DEVICE_SERVICE, 3, METHOD_BUFFERED, FILE_ANY_ACCESS)rnrn//////////////////////////////////////////////////////////////////////////rn//rnrnrnGUID RFCOMM_PROTOCOL_UUID = 0x00001101, 0x0000, 0x1000, 0x80, 0x00, 0x00, 0x80, 0x5F, 0x9B, 0x34, 0xFB;rnrnHKEY m_hKey;rn//rnHWND m_hwnd_List_Find;rnTCHAR wRbuf[64];rn//rn#define NS_BTH 16rn//rn#define MAX_NAME 248rnrn//rnrnrn//rnSOCKET m_socket;rn//rn//rnLPWSAQUERYSET pwsaResults;rn//rnCStringArray csar;rnunsigned short g_port;rnrnrnUINT m_LinkState; //连接活动进行到什么状态rn#define DEFAULT_PORT 1rnrn//保存蓝牙设备 BT_ADDRrnCArray arb;rnrnrnHWND hWnd;rnBOOL nExit = FALSE;rnHANDLE hThread = INVALID_HANDLE_VALUE;rnstatic DWORD WINAPI ReadThread( PVOID pArg );rnrnIMPLEMENT_DYNCREATE(CBthOpe4View, CFormView)rnrnBEGIN_MESSAGE_MAP(CBthOpe4View, CFormView)rn ON_BN_CLICKED(IDC_BUT_FIND, &CBthOpe4View::OnBnClickedButFind)rn ON_WM_CLOSE()rn ON_BN_CLICKED(IDC_BUT_LINK, &CBthOpe4View::OnBnClickedButLink)rn ON_BN_CLICKED(IDC_BTN_SEND, &CBthOpe4View::OnBnClickedBtnSend)rn ON_WM_TIMER()rnEND_MESSAGE_MAP()rnrn// CBthOpe4View 构造/析构rnrnCBthOpe4View::CBthOpe4View()rn : CFormView(CBthOpe4View::IDD)rnrn // TODO: 在此处添加构造代码rnrnrnrnCBthOpe4View::~CBthOpe4View()rnrnrnrnvoid CBthOpe4View::DoDataExchange(CDataExchange* pDX)rnrn CFormView::DoDataExchange(pDX);rnrnrnBOOL CBthOpe4View::PreCreateWindow(CREATESTRUCT& cs)rnrn // TODO: 在此处通过修改rn // CREATESTRUCT cs 来修改窗口类或样式rnrn return CFormView::PreCreateWindow(cs);rnrnrnrnrnvoid CBthOpe4View::OnInitialUpdate()rnrn CFormView::OnInitialUpdate();rnrn m_LinkState = 0;rn SetTimer(1,100,NULL);rnrn GetDlgItem( IDC_LIST_FIND, &m_hwnd_List_Find );rn WSADATA wsd;rn int ret = WSAStartup( MAKEWORD( 2, 2 ), &wsd );rn WCHAR *argPtr = _T("card");rn HANDLE hDev = CreateFile (L"BTD0:", GENERIC_READ | GENERIC_WRITE, //打开电源rn FILE_SHARE_READ | FILE_SHARE_WRITE,NULL, OPEN_EXISTING, 0, NULL);rn rn if (hDev != INVALID_HANDLE_VALUE) rn rn int iErr = DeviceIoControl (hDev, IOCTL_SERVICE_START, argPtr, sizeof(WCHAR) * (wcslen (argPtr) + 1), NULL, NULL, NULL, NULL);rn CloseHandle (hDev);rn rn rn nExit = TRUE;rn hThread = CreateThread(NULL,0, ReadThread,NULL, 0,NULL);rnrn Sleep(1000);rnrnrnrn// CBthOpe4View 诊断rnrn#ifdef _DEBUGrnvoid CBthOpe4View::AssertValid() constrnrn CFormView::AssertValid();rnrnrnCBthOpe4Doc* CBthOpe4View::GetDocument() const // 非调试版本是内联的rnrn ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CBthOpe4Doc)));rn return (CBthOpe4Doc*)m_pDocument;rnrn#endif //_DEBUGrnrnrn// CBthOpe4View 消息处理程序rnrnvoid CBthOpe4View::OnBnClickedButFind()rnrn // TODO: 在此添加控件通知处理程序代码rn if ( TRUE == m_BSoketFlag ) rn rn m_BSoketFlag = FALSE;rn closesocket( m_socket );rn rnrn ((CListBox*)GetDlgItem(IDC_LIST_FIND))->ResetContent();rnrn GetDlgItem(IDC_BUT_FIND)->EnableWindow( FALSE );rn PerformInquiry();rn GetDlgItem(IDC_BUT_FIND)->EnableWindow( TRUE );rnrn//////////////////////////////////////////////////////////////////////////rnBOOL CBthOpe4View::Open( )rnrn unsigned int channel = 0;rnrn //创建TCP套接字 rn m_socket = socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM);rn if (m_socket == INVALID_SOCKET)rn return FALSE;rnrn return TRUE;rnrn//查询蓝牙设备rnBOOL CBthOpe4View::PerformInquiry() rnrn int ret ;rn int count = 0;rn int retry = 0 ;rnrn arb.RemoveAll();rn csar.RemoveAll();rn rn WSAQUERYSET wsaq;rn HANDLE hLookup;rn union rn CHAR buf[5000];rn double __unused; // ensure proper alignmentrn ;rn rn Open();rnrn /*LPWSAQUERYSET*/ pwsaResults = (LPWSAQUERYSET) buf;rn DWORD dwSize = sizeof(buf);rn BOOL bHaveName;rn //搜索其它蓝牙设备 rnrn ZeroMemory(&wsaq, sizeof(wsaq));rn wsaq.dwSize = sizeof(wsaq);rn wsaq.dwNameSpace = NS_BTH;rn wsaq.lpcsaBuffer = NULL;rnrn ret = WSALookupServiceBegin(&wsaq, LUP_CONTAINERS, &hLookup);rn if(ERROR_SUCCESS != ret)rn rn wprintf(L"WSALookupServiceBegin failed %d\r\n", GetLastError());rn return FALSE;rn rnrn ZeroMemory(pwsaResults, sizeof(WSAQUERYSET));rn pwsaResults->dwSize = sizeof(WSAQUERYSET);rn pwsaResults->dwNameSpace = NS_BTH;rn pwsaResults->lpBlob = NULL;rn while (1)rn rn ret = WSALookupServiceNext(hLookup, rn LUP_RETURN_NAME | LUP_RETURN_ADDR, rn &dwSize, pwsaResults);rn if(ret != ERROR_SUCCESS)rn rn ret = WSAGetLastError();rn break;rn rnrn ASSERT (pwsaResults->dwNumberOfCsAddrs == 1);rn BT_ADDR b = ((SOCKADDR_BTH *)pwsaResults->lpcsaBuffer->RemoteAddr.lpSockaddr)->btAddr;rn rn g_port = ((sockaddr_in*)pwsaResults->lpcsaBuffer->RemoteAddr.lpSockaddr)->sin_port;rn //if(g_port == 0)rn g_port = DEFAULT_PORT;rnrn bHaveName = pwsaResults->lpszServiceInstanceName && *(pwsaResults->lpszServiceInstanceName);rn // for testrn arb.Add( b );rn WCHAR szDevice[MAX_NAME+25];rn wsprintf (szDevice, L"%s%s%04x%08x%s", bHaveName ? pwsaResults->lpszServiceInstanceName : L"", rn bHaveName ? L"(" : L"", GET_NAP(b), GET_SAP(b), bHaveName ? L")" : L"");rn rn CString csDevice = szDevice;rn // for testrn csar.Add( csDevice );rn ListBox_AddString( m_hwnd_List_Find, csDevice); rn //MessageBox(csDevice);rn rn count ++ ;rn rn WSALookupServiceEnd(hLookup);rnrn if(!count)rn rn AfxMessageBox(_T("搜索失败"));rn return FALSE ;rn rn return TRUE;rnrn
蓝牙Socket通讯
前段时间写了蓝牙gatt协议的通讯,发现Android开发蓝牙,与硬件通讯使用gatt协议。如果个Android设备之间开发蓝牙通讯该怎么写。就在查了有关方面的资料,了解了Socket通讯,今天就写下Android设备之间的蓝牙Socket通讯。首先你得有两部Android设备,一个作为服务器,一个作为客户端。我把服务器与客户端的代码都写在同一个工程中,只需要选择当前设备是作为服务器,还是客户端就...
android开发蓝牙连接其他蓝牙设备时socket.connect失败怎么解决
用Android studio写了个程序来连接其他设备,但在连接时候出了问题,报错read failed, socket might closed or timeout, read ret: -1,似乎都是socket.connect出问题,uuid也换了挺多都不行,也试过用端口设1值连接,也试过再开个进程来连,但都还是不行,想问问各位怎么解决![图片说明](https://img-ask.csdn.net/upload/201710/30/1509296890_993466.png)n没有多少悬赏了只能这些了n拜托各位解决一下
VS2005的环境下用winsock开发蓝牙,socket()失败,求教
刚开始学习socket编程,希望大侠们帮帮忙,谢谢.rnrn我的程序server端在winxp sp2上运行总是不能创建socket,rn错误是10047:使用的地址与被请求的协议不兼容rnrn代码如下:rnrn#include rn#include rnrn ......rn ......rnrn int iRes = 0;rn WSADATA wsd;rn if(0 != WSAStartup(MAKEWORD(2,2),&wsd))rn rn iRes = WSAGetLastError();rn MessageBox(L"Initial failed");rn rnrn SOCKET server_socket = socket(AF_BT, SOCK_STREAM, BTHPROTO_RFCOMM);rn if(server_socket == INVALID_SOCKET)rn rn iRes = WSAGetLastError();rn MessageBox(L"Create Socket Error ");rn rnrn ......rn ......
在PC上开发蓝牙应用程序 建立socket失败?
系统: Windows7 rnSDK: Windows SDK 7.1rn开发平台:VS2008 rnUSB口的蓝牙,驱动是IVT的, 已开启rn rn代码:rn [code=C/C++] if (0 == ::WSAStartup(wVersionRequested, &m_data))rn rn SOCKET s = ::socket(AF_BTH, SOCK_STREAM, BTHPROTO_RFCOMM); rnrn const DWORD lastError = ::GetLastError();rnrn if (s == INVALID_SOCKET)rn rn printf("Failed to get bluetooth socket! %s\n", GetLastErrorMessage(lastError));rn exit(1);rn rn [/code]rn结果 socket 返回 10047, 即使用了与请求协议不兼容的地址rnrn请问怎么办? 谢谢!
c# socket.connect超时
c# 如何设置 socket.connect超时时间?rnrn因为如果不设置的话,对方不开机,得等大约一分钟才能跳出等待.怎么设置timeout时间呢?
socket.connect的返回值是什么?
如下语句:rnIPAddress ip = IPAddress.Parse( "127.0.0.1 "); rntry rnIPEndPoint point = new IPEndPoint(ip,port); rnSocket sock = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); rnsock.Connect(point); //就这一句,不知道返回值是什么?rnrncatch(SocketException e) rn rn
情态动词 may/might
情态动词 may/might之前我们已经讲过情态动词可以有2种时态:现在时、过去时。 这里may就可以表示现在,might表示过去。 另外might也可以不表示过去,而表示更加委婉的语气。用法1.推测 “可能”The paly [may begin] at any moment. #may+动词原形,推测现在 It 【may have begun】 already. #may have d
socket.connect(socketAddress,timeout ))
[color=#FF0000]接口中的一个方法:向某个IP服务器下的某port 通过Socket 传入 request字符串,结果服务器处理返回 response字符串rn问题:服务器端是怎么实现的?也就是说他是怎么监听有数据需要处理的s时候进行及时的处理?开始我想到ServerSocket但这是web工程主要怎么来实现呢?rnrn[/color]rn rnrn[code=Java]rnpublic String reuqestTrade(String request, String url, String port,rn String encode) rn String str = "ERROR";rn Socket socket = null;rn OutputStream os;rn InputStream is;rn try rn socket = new Socket(); // 客户端给出IP和端口号rn SocketAddress socketAddress = new InetSocketAddress(url, rn Integer.parseInt(port.trim()));rn socket.connect(socketAddress, Integer.parseInt(Helprn .getUrl("timeout")));rn log.info("socket(客服端未限制端口) 已连接-->" + url + ":" + port);rn is = socket.getInputStream();rn os = socket.getOutputStream();rnrn os.write(request.getBytes());rn os.flush();rnrn byte[] serByte = new byte[2048];rn String serverStr = null;rn int flag = is.read(serByte);rn if (flag != -1) rn serverStr = new String(serByte);rn rn log.info(" answer --> " + serverStr);rn return serverStr;rn catch (UnknownHostException e) rn log.error("systemerr", e);rn str = "ERROR";rn return str;rn catch (IOException e) rn log.error("systemerr", e);rn str = "ERROR";rn return str;rn finally rn if (socket != null) rn try rn socket.close();rn catch (IOException e) rn log.error("systemerr", e);rn str = "ERROR";rn return str;rn rn rn rn rn[/code]
Android蓝牙
Android蓝牙
Android与蓝牙
如果android开发板有一个外设,该外设通过蓝牙,接收无线传感器传过来的数据,要怎么去做才能把这些数据读取出来,该怎么做?有没有好的源码实例让我学习下,或者给个具体点的思路,大虾们!谢了!
Android Socket访问外网IP 失败 求教
现在有两个java程序,一个运行在服务器端,一个运行在客户端: rn 在局域网的时候将两段程序中的 xxx.xxx.xxx.xxx 都设定为服务器的IP时程序能够正常运行。 rn 现在将服务器端的程序运行在局域网的一台服务器上,这台服务器对应两个IP,一个是内网的IP10.22.60.28,一个是外网的IP210.52.23.14,通过外网IP访问这台服务器时要经过NAT转换,换成10.22.60.28再访问。 rn 问题:客户端程序运行在外网的一台主机上,想将客户端xxx.xxx.xxx.xxx 设为210.52.23.14来与服务器上的程序建立连接,但服务端没有反应,请高手指导一下! rnrnrn服务器端: rnpackage com.server; rnimport java.net.*; rnimport java.io.*; rnpublic class MyServer rn public static void main( String args[]) rn ServerSocket serverSocket = null; rn Socket socket = null; rn String inputLine = null ; rn rn try rn InetAddress address=InetAddress.getByName(" xxx.xxx.xxx.xxx");//本地IP rn serverSocket = new ServerSocket(61008,50,address); rn socket = serverSocket.accept() ; rn rn System.out.println(socket.toString()); rn rn PrintWriter out = new PrintWriter(socket.getOutputStream(), true); rn BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream())); rn rn while ((inputLine = in.readLine()) != null) rn System.out.println( inputLine +"1231") ; rn rn out.close(); rn in.close(); rn socket.close(); rn catch( Exception e ) rn System.out.println( e ) ; rn rn rn rnrn客户端: rnpackage com.client; rnimport java.io.*; rnimport java.net.*; rnpublic class MyClient rn public static void main(String[] args) throws IOException rn Socket kkSocket = null; rn PrintWriter out = null; rn BufferedReader in = null; rn try rn kkSocket = new Socket(" xxx.xxx.xxx.xxx", 61008); //指定要连接的公网IP地址及端口号。 rn rn out = new PrintWriter(kkSocket.getOutputStream(), true); rn in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream())); rn out.println("hello"); rn in.close(); rn out.close(); rn kkSocket.close(); rn catch (UnknownHostException e) rn System.err.println("Don't know about host: taranis."); rn System.exit(1); rn rn rn rnrn
相关热词 c# 去空格去转义符 c#用户登录窗体代码 c# 流 c# linux 可视化 c# mvc 返回图片 c# 像素空间 c# 日期 最后一天 c#字典序排序 c# 截屏取色 c#中的哪些属于托管机制