连接时,给服务端发送数据时总是报错!!
11-28 11:15:36.164: D/MainActivity(4212): wifiname:"LcyAP_03001" prxFlag:true substr: LcyAP FirstConn:true
11-28 11:15:36.164: D/MainActivity(4212): Now Ready to create connect to LC:Now wifi stat is:SSID:"LcyAP_03001"wificonnsetat:trueSrvIp:192.168.173.1
11-28 11:15:36.164: W/System.err(4212): java.net.SocketException: Socket is closed
11-28 11:15:36.174: W/System.err(4212): at java.net.Socket.checkOpenAndCreate(Socket.java:675)
11-28 11:15:36.174: W/System.err(4212): at java.net.Socket.getOutputStream(Socket.java:415)
11-28 11:15:36.174: W/System.err(4212): at cn.LCSys.socket.TCPClient.sendMsg(TCPClient.java:104)
11-28 11:15:36.174: W/System.err(4212): at cn.LCSys.MainActivity$4.run(MainActivity.java:410)
11-28 11:15:36.174: W/System.err(4212): at java.lang.Thread.run(Thread.java:841)
11-28 11:15:38.194: D/MainActivity(4212): wifiname:"LcyAP_03001" prxFlag:true substr: LcyAP FirstConn:true
11-28 11:15:38.194: D/MainActivity(4212): Now Ready to create connect to LC:Now wifi stat is:SSID:"LcyAP_03001"wificonnsetat:trueSrvIp:192.168.173.1
11-28 11:15:38.194: W/System.err(4212): java.net.SocketException: Socket is closed
11-28 11:15:38.194: W/System.err(4212): at java.net.Socket.checkOpenAndCreate(Socket.java:675)
11-28 11:15:38.194: W/System.err(4212): at java.net.Socket.getOutputStream(Socket.java:415)
11-28 11:15:38.194: W/System.err(4212): at cn.LCSys.socket.TCPClient.sendMsg(TCPClient.java:104)
11-28 11:15:38.194: W/System.err(4212): at cn.LCSys.MainActivity$4.run(MainActivity.java:410)
11-28 11:15:38.204: W/System.err(4212): at java.lang.Thread.run(Thread.java:841)
客户端代码为:
package cn.LCSys.socket;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import cn.LCSys.MainActivity;
import cn.LCSys.fragment.SystemSetting;
import android.content.Intent;
import android.os.SystemClock;
import android.util.Log;
public class TCPClient {
private String TAG = "TCP Client";
private static TCPClient s_Tcp = null;
// 要连接的服务器Ip地址
private String SrvIp;
// 要连接的远程服务器在监听的端口
private int SrvPort;
public boolean isInitialized = false;
private boolean bConnect;
Socket socket = null ;
private long LastTickCount;
public static synchronized TCPClient instance()
{
if (s_Tcp == null)
{
{
s_Tcp = new TCPClient(Const.SOCKET_SERVER,
Const.SOCKET_PORT);
}
}
return s_Tcp;
}
public TCPClient(String HostIp, int HostListenningPort)
{
LastTickCount = 0;
Log.d(TAG,"SrvIP:["+HostIp+"]SrvPort:["+HostListenningPort+"].");
this.SrvIp = HostIp;
this.SrvPort = HostListenningPort;
bConnect = false;
try
{
start();
} catch (Exception e)
{
this.isInitialized = false;
Log.d(TAG," TCPClient Initialize catch err!"+e.getMessage());
e.printStackTrace();
}
}
public static final Object locked = new Object();
public static final BlockingQueue<String> queue = new ArrayBlockingQueue<String>(
1024 * 100);
//通过数据接收判断是否链路正常 10秒没有数据认为链路异常,进行重新连接
class EchoThread extends Thread{
private Socket socket;
@Override
public void run() {
while(isInitialized){
try {
if(LastTickCount > 0)
{
//10
if((System.currentTimeMillis() - LastTickCount) > Const.SOCKET_TIMOUT)
{
bConnect = false;
LastTickCount = 0;
}
}
SystemClock.sleep(500);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
//发送数据
public boolean sendMsg(String sendMsg) throws InterruptedException{
try {
PrintWriter pw = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
pw.write(sendMsg);
pw.flush();
return true;
} catch (Exception e)
{
bConnect = false;
e.printStackTrace();
return false;
}
}
//}
// 接收数据的线程
class ReceiveThread extends Thread
{
private Socket socket;
public ReceiveThread(Socket socket)
{
this.socket = socket;
}
@Override
public void run()
{
String receivedString;
CharBuffer charBuffer = CharBuffer.allocate(4096);
while(isInitialized){
try {
Reader reader = new InputStreamReader(socket.getInputStream());
charBuffer.clear();
int index = -1;
while((index=reader.read(charBuffer))!=-1)
{
LastTickCount = System.currentTimeMillis();
charBuffer.flip();
//System.out.println("client:"+charBuffer.toString());
Charset cs = Charset.forName("UTF-8");
receivedString = cs.encode(charBuffer).toString() ;
int readlen = receivedString.length();
if( readlen > 100)
{
//无法获取到数据
/*receivedString = Charset.forName("US-ASCII")
.newDecoder().decode(buffer).toString();*/
// mylcHandle.ColldataHandle(receivedString);
Log.d(TAG,"Read Data Length: "+readlen);
}
else
{
Log.d(TAG, "Recv len:"+readlen+" Content:"+receivedString);
}
Intent i = new Intent(Const.BC);//广播消息,实现类之间的交互
i.putExtra("response", receivedString);
MainActivity.s_context.sendBroadcast(i);
//给系统配置广播数据
if(null!= SystemSetting.s_context)
{
Log.d(TAG, "Broad to SystemSetting:"+readlen);
SystemSetting.s_context.sendBroadcast(i);
}
//给实时数据fragement广播数据
/*
if(null!= FragmentRealData.s_context)
{
Intent ii = new Intent(Const.DATABC);
ii.putExtra("response", receivedString);
Log.d(TAG, "Broad to FragmentRealData:"+readlen);
FragmentRealData.s_context.sendBroadcast(ii);
}*/
charBuffer.clear();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
public void start() throws UnknownHostException, IOException{
socket = new Socket(SrvIp,SrvPort);
if(socket != null)
{
bConnect = true;
isInitialized = true;
new ReceiveThread(socket).start();
}
else
{
bConnect = false;
}
}
boolean isConnect()
{
return bConnect;
}
public void closeTCPSocket()
{
try{
if(socket!= null)
{
socket.close();
isInitialized = false;
}
}
catch(Exception ex)
{
Log.e(TAG,"Close Socket error!");
}
}
// public static void main(String[] args) throws UnknownHostException, IOException {
// new TCPClient().start();
// }
}