解决方案 »
- 网络音乐播放器问题
- android音乐播放器中专辑封面怎么得到??
- 关于sharedpreferences存储
- 关于Bitmap的内存泄露问题
- 请问android如何让父窗口上背景的长宽 自动适应 和它上面子窗口所占长宽的大小一样呢?
- imageButton 报错空指针
- 通知栏点击后消失
- apk修改strings.xml后重新打包出错
- logcat怎么看啊
- android网页分享到朋友圈问题求助?
- 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;
}}