解决方案 »
- android 从内存中安装apk
- 怎样禁用掉屏幕上右下角的关于电池电量等的图标?
- android的系统字体如何更改,整个系统一起改动
- android 下载问题
- 关于蓝牙的问题
- android小菜鸟 问一个关于进程的小问题
- 菜鸟提问:按钮链接问题....急
- 请问SyncAdapter里定时同步addPeriodicSync为什么不会调用
- 刚刚入门~写程序遇到点问题~希望有人可以帮忙看看~
- 安卓平台怎么使用.so或.a文件
- android下用ViewPager或者ViewFlow加载Activity,但是自定义的Activity切换动画失效
- 共同学习,对invalidate和postInvalidate的理解和理解上的一些问题??
public static boolean ISCONNECT;
static Socket socket;
static OutputStream output;
static InputStream input;
private static String ip;
private static int port;
private Thread socThread = null;
private byte[] readbuffer = null; /**
* 创建客户端到服务器的连接Socket
*
* @param ip
* @param port
* @throws IOException
*/
public TcpSocket(String ip, int port) {
TcpSocket.ip = ip;
TcpSocket.port = port; } public boolean SocConnect() throws IOException {
boolean re = true;
if (socket == null) {
try {
InetAddress address = InetAddress.getByName(ip);
socket = new Socket(address, port);
TcpSocket.ISCONNECT = true; socThread = new Thread() {
@Override
public void run() {
while (!isInterrupted()) {
if (SocReceive().length > 0) {
OnReceive.OnReceive(readbuffer);
} }
}
};
} catch (ConnectException ce) {
socket = null;
// throw ce;
re = false;
} catch (IOException e) {
SocClose();
// throw e;
re = false;
}
}
return re;
} /**
* 发送字节数组
*
* @param bytes
* @throws IOException
*/
public void SocSend(byte[] bytes) throws IOException {
try {
output = socket.getOutputStream();
output.write(bytes);
output.flush();
// output.close();
} catch (IOException e) {
SocClose();
throw e;
} } /**
* 接收字节数组并填充
*
* @param bytes
* @return
* @throws IOException
*/
public byte[] SocReceive() {
int len;
byte[] readbuf = new byte[1024]; try {
if (input.available() > 0) {
len = input.available();
readbuffer = new byte[len];
int count = 0;
while (count < readbuffer.length) {
count += input.read(readbuffer, count, readbuffer.length
- count);
} return readbuffer;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return readbuffer;
} public int receive(byte[] bytes) throws IOException {
int rece = 0;
try {
input = socket.getInputStream();
rece = input.read(bytes);
OnReceive.OnReceive(bytes);
// input.close();
return rece;
} catch (IOException e) {
SocClose();
throw e;
}
} public void SocClose() throws IOException {
try {
if (output != null)
output.close();
if (input != null)
input.close();
if (socket != null) {
socket.close();
socket = null;
}
TcpSocket.ISCONNECT = false;
if (null != socThread) {
socThread.stop();
socThread = null;
}
} catch (IOException e) {
throw e;
}
} public SocOnReceiveDataHandleEvent OnReceive = null; public interface SocOnReceiveDataHandleEvent {
public void OnReceive(byte[] bytes);
} public SocOnReceiveDataHandleEvent getOnReceive() {
return OnReceive;
} public void setOnReceive(SocOnReceiveDataHandleEvent onReceive) {
OnReceive = onReceive;
}}