Android手机通过与PC通讯的问题
先上码,
主Activity:
public class MainActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); new Thread() { @Override public void run() { beginRun(); } }; } @Override protected void onStop() { // TODO Auto-generated method stub super.onStop(); MainService.ISRUN = false; } private void beginRun() { try { ServerSocket serverSocket = new ServerSocket(5566); Socket client = serverSocket.accept(); new Thread(new SocketThread(client)).start(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
public class SocketThread implements Runnable { private static final String TAG = "SocketThread"; private static final int MAX_BUFFER_BYTES = 2048; private static final String ENCODING = "UTF-8"; private Socket client; public SocketThread(Socket client) { this.client = client; } @Override public void run() { Log.d(TAG, "---服务线程启动..."); BufferedInputStream in = null; BufferedOutputStream out = null; try { in = new BufferedInputStream(client.getInputStream()); out = new BufferedOutputStream(client.getOutputStream()); while (MainService.ISRUN) { if (!client.isConnected()) break; String cmd = readCMD(in); System.out.println("收到:" + cmd); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { out.close(); in.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Log.d(TAG, "----线程关闭"); } } private String readCMD(InputStream in) { byte[] bufferBytes = new byte[MAX_BUFFER_BYTES]; String cmd = null; try { int readBytesCount = in.read(bufferBytes); cmd = new String(bufferBytes, 0, readBytesCount); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return cmd; }}
public class Main { private static final String HOST = "127.0.0.1"; private static final int PORT = 55666; private static Socket pc; public static void main(String[] args) { try { InetAddress address = InetAddress.getByName(HOST); pc = new Socket(address, PORT); BufferedOutputStream out = new BufferedOutputStream( pc.getOutputStream()); int i = 1; while (true) { String msg = i++ + "你妹的";// out.write(msg.getBytes()); out.write(3); out.flush(); Thread.sleep(3000); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } }}
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
at java.io.BufferedOutputStream.flush(Unknown Source)
at Main.main(Main.java:25)
[解决办法]
一个是5566 一个是55666 擦擦擦