|
1、添加权限
<uses-permission android:name="android.permission.INTERNET" />
2、例程:- public class ClientSocket {
- static BufferedReader in;
- static PrintWriter out;
- public static Boolean SendMsg(MyData myData) {
- char[] bRecvBuff = new char[4096];
- boolean bSuccess = false;
- String strRecv = null;
- myData.setStatus(Utility.SEND_FAIL);
- FileInputStream fis = null;
- DataOutputStream dos = null;
- int length = 0;
- try {
- Socket client = null;
- SocketAddress address;
- if (myData.getType() == 0) {
- address = new InetSocketAddress(Utility.SERVERIP,
- Utility.SERVERPORT);
- } else {
- address = new InetSocketAddress(Utility.SERVERIP,
- Utility.SERVERPORT + 1);
- }
- client = new Socket();
- client.connect(address, 5000);
- client.setSoTimeout(5000);
- client.setTcpNoDelay(true);
-
- client.setSoLinger(true, 60);
-
- client.setSendBufferSize(8096);
- client.setReceiveBufferSize(8096);
- client.setKeepAlive(true);
- in = new BufferedReader(new InputStreamReader(
- client.getInputStream(), "utf-8"));
- String str = myData.getData();
- if (myData.getType() == 0) {
- out = new PrintWriter(client.getOutputStream());
- BufferedReader line = new BufferedReader(new InputStreamReader(
- new ByteArrayInputStream(str.getBytes())));
- char buf[] = new char[2048];
- while (line.read(buf) > 0) {
- line.read(buf);
- Log.d("send:", String.valueOf(buf));
- out.println(buf);
- }
- out.flush();
- } else {
- dos = new DataOutputStream(client.getOutputStream());
- File file = new File(str);
- fis = new FileInputStream(file);
- byte sendBytes[] = new byte[str.getBytes().length];
- dos.writeByte(myData.getType());
- dos.writeBytes(Utility.ENC_TOKEN);
- dos.flush();
- while ((length = fis.read(sendBytes, 0, sendBytes.length)) > 0) {
- dos.write(sendBytes, 0, length);
- dos.flush();
- }
- client.shutdownOutput();
- if (fis != null)
- fis.close();
- }
- strRecv = "";
- int iRecvLen = in.read(bRecvBuff);
- if (iRecvLen > 0) {
- bRecvBuff[iRecvLen] = 0x00;
- strRecv = String.valueOf(bRecvBuff);
- strRecv = strRecv.substring(0, iRecvLen);
- }
- if (strRecv != null) {
- myData.setData(strRecv);
- myData.setStatus(Utility.RECV_SUCCESS);
- bSuccess = true;
- } else {
- myData.setStatus(Utility.RECV_FAIL);
- strRecv = "Please check the Socket connection!";
- }
- Log.d("Socket recieve", strRecv);
- // line.close();
- if (out != null)
- out.close();
- in.close();
- client.close();
- } catch (UnknownHostException e) {
- myData.setStatus(Utility.SEND_FAIL);
- strRecv = "Please check the Socket connection!";
- e.printStackTrace();
- } catch (IOException e) {
- myData.setStatus(Utility.SEND_FAIL);
- strRecv = "Please check the Socket connection!";
- e.printStackTrace();
- }
- return bSuccess;
- }
- }
复制代码
|
|