Android应用Socket与PC通信失败

服务器端

 import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPDesktopServer implements Runnable{


    public static final String SERVERIP = "192.168.155.1";

    public static final int SERVERPORT = 1920;


    public void run() {

         try {

             System.out.println("S: Connecting...");

             ServerSocket serverSocket = new ServerSocket(SERVERPORT);

             while (true) {

                  Socket client = serverSocket.accept();

                  try {

                      BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));

                      String str = in.readLine();

                      System.out.println("S: Received: '" + str + "'");

                    } catch(Exception e) {

                        System.out.println("S: Error");

                        e.printStackTrace();

                    } finally {

                        client.close();

                        System.out.println("S: Done.");

                    }

             }

          } catch (Exception e) {

             System.out.println("S: Error");

             e.printStackTrace();
         }
    }

   public static void main (String a[]) {

        Thread ServerThread = new Thread(new TCPDesktopServer());

        ServerThread.start();
    }
}

客户端、

 package com.ldgforever.controlbywifi;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class LightControlActivity extends Activity {

    private Button mBtnSend;                
    private static final String TAG = "com.ldgforever.controlbywifi";
    private String mIPAdress;
    private int mPortNumber;
    String ip="192.168.155.1";
    int port=1920;
    Socket socket = null;

    private String mSendMsg = "test";

    public static final String EXTRA_RECEIVE_IP = 
            "com.ldgforever.controlbywifi.receive_ip";
    public static final String EXTRA_RECEIVE_PORT = 
            "com.ldgforever.controlbywifi.receive_port";    

@Override
protected void onCreate(Bundle savedInstanceState){
      super.onCreate(savedInstanceState);
      setContentView(R.layout.light_control);


      mIPAdress = getIntent().getStringExtra(EXTRA_RECEIVE_IP);
      mPortNumber = Integer.parseInt(getIntent()
               .getStringExtra(EXTRA_RECEIVE_PORT));  

      mBtnSend = (Button)findViewById(R.id.send_data);
      mBtnSend.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            SetOnClick();
            }
    });
}

private void SetOnClick()
{   
            // TODO Auto-generated method stub
        try {
                if(!TextUtils.isEmpty(mSendMsg))
                        SendMsg(ip,port,mSendMsg);
                else
                {
                    Toast.makeText(LightControlActivity.this,"msg is EMPTY!!", Toast.LENGTH_LONG).show();
                }
        } catch (UnknownHostException e) {
                        // TODO Auto-generated catch block
                        Toast.makeText(LightControlActivity.this,"!UnknownHostException!", Toast.LENGTH_LONG).show();
                        e.printStackTrace();
        } catch (IOException e) {
                        // TODO Auto-generated catch block
                        Toast.makeText(LightControlActivity.this,"!IOException!", Toast.LENGTH_LONG).show();
                        e.printStackTrace();
        }catch (Exception e) {   //每次都断在这里
                        // TODO Auto-generated catch block
                        Log.e(TAG, "Exception");
                        Toast.makeText(LightControlActivity.this,"!Exception!", Toast.LENGTH_LONG).show();
                        e.printStackTrace();
            }

}

public void SendMsg(String ip,int port,String msg) throws UnknownHostException, IOException
{
    try
    {
      socket = new Socket();  
      socket=new Socket(ip,port); 
      PrintWriter writer = new PrintWriter(new BufferedWriter
              (new OutputStreamWriter(socket.getOutputStream())));
//    BufferedWriter writer=new BufferedWriter(new OutputStreamWriter
//              (socket.getOutputStream()));
//      writer.write(msg);
        writer.println(msg);
        writer.flush();
        writer.close();       
        socket.close();
    }
    catch(UnknownHostException e)
    {
        Log.e(TAG, "UnknownHostException");
        e.printStackTrace();
    } catch (IOException e) 
    {
        Log.e(TAG, "IOException");
        e.printStackTrace();
    }
}
}

是通过mainactivity打开这个activity 网络权限添加了 不知道为什么客户端单拿出来写一个edittext 和button的发送小程序就好使

3个回答

已经解决 在这里说明一下答案 两种解决办法。。1.异步通信 2.放在thread.run()中

1、对于连接失败的问题,查看下面的三个权限是否开启:



2、对于logcat的问题,建议查看“android sdk r23 ndk 10 的环境配置文档和视频”中的
“android ndk 开发建议”;

1、对于连接失败的问题,查看下面的三个权限是否开启:



2、对于logcat的问题,建议查看“android sdk r23 ndk 10 的环境配置文档和视频”中的
“android ndk 开发建议”;

feng1790291543
鱼弦 1、对于连接失败的问题,查看下面的三个权限是否开启: <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET" /> 2、对于logcat的问题,建议查看“android sdk r23 ndk 10 的环境配置文档和视频”中的 “android ndk 开发建议”;
3 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问