importjava.io.IOException;importjava.net.InetAddress;importjava.net.ServerSocket;importjava.net.Socket;public class TcpConnect implementsRunnable{private final int SERVER_PORT = 10086;privateServerSocket mServerSocket;privateSocket mClient;privateString mDeviceId;privateString mDeviceType;publicTcpConnect(String aDeviceId, String aDeviceType){this.mDeviceId=aDeviceId;this.mDeviceType =aDeviceType;try{
String ip=InetAddress.getLocalHost().getHostAddress();
System.out.println("ip地址是: " +ip);//System.out.println(aDeviceId + " 型号: " + aDeviceType);
mServerSocket = newServerSocket(SERVER_PORT);
System.out.println("TcpConnect" + "建立Socket");//listen();
}catch(IOException e) {//TODO Auto-generated catch block//e.printStackTrace();
System.out.println("TcpConnect" +e.getMessage());
}
}public voidlisten(){while(true){try{
mClient=mServerSocket.accept();//Log.e("TcpConnect", "在积极的监听");}catch(IOException e) {//TODO Auto-generated catch block//e1.printStackTrace();
System.out.println("TcpConnect" +e.getMessage());
}
}
}
@Overridepublic voidrun() {//TODO Auto-generated method stub//if(mClient.isConnected()){
BufferedOutputStream out = null;
System.out.println("TcpConnect" + "开始监听");while(true){try{//Log.e("TcpConnect", "开始监听");
mClient =mServerSocket.accept();//if(mClient.isConnected()){
System.out.println("TcpConnect" + "检测到有连接");
out= newBufferedOutputStream(mClient.getOutputStream());
String recordStr= mDeviceId + "|" +mDeviceType;
out.write(recordStr.getBytes("utf-8"));//int length = recordStr.getBytes().length;//byte[] b = recordStr.getBytes();//out.writeInt(length);//out.write(b);
out.flush();//Log.e("TcpConnect", recordStr);//out.flush();//}
} catch(Exception e){
System.out.println("TcpConnect" +e.getMessage());
}finally{if(out != null){try{
out.close();
}catch(IOException e) {//TODO Auto-generated catch block
System.out.println("TcpConnect" +e.getMessage());
}
}if(mServerSocket != null){try{
mServerSocket.close();
}catch(IOException e) {//TODO Auto-generated catch block
System.out.println("TcpConnect" +e.getMessage());
}
}//}
}
}
}public static voidmain(String[] args){new Thread(new TcpConnect("2366578546946", "T959")).start();
}
}