服务器/客户端Android到PC通信问题

时间:2011-11-08 04:02:17

标签: java android sockets tcp

我试图使用具有Android手机作为客户端的插槽编写程序,我的PC作为服务器我发现并略微修改了双方的代码和我的服务器代码工作,但我无法得到客户端活动和我不知道如何让程序说话,我想基本上能够有任何一方输入文本,并让它发送和设置可见到另一个我知道你们有多少问题,所以..我如何让这些沟通?

客户端代码(模拟器在我甚至可以开始看到问题之前崩溃)

package com.example.Socket;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.*;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.*;
import java.net.*;


public class ClientActivity extends Activity {

    private EditText serverIp;

    private Button connectPhones;

    private String serverIpAddress = "";

    private boolean connected = false;

    private Handler handler = new Handler();

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

        serverIp = (EditText) findViewById(R.id.server_ip);
        connectPhones = (Button) findViewById(R.id.connect_phones);
        connectPhones.setOnClickListener((android.view.View.OnClickListener) connectListener);
    }

    private OnClickListener connectListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            if (!connected) {
                serverIpAddress = serverIp.getText().toString();
                if (!serverIpAddress.equals("")) {
                    Thread cThread = new Thread(new ClientThread());
                    cThread.start();
                }
            }
        }
    };

    public class ClientThread implements Runnable {

        public void run() {
            try {
                InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
                Log.d("ClientActivity", "C: Connecting...");
                Socket socket = new Socket(serverAddr, 9999);
                connected = true;
                while (connected) {
                    try {
                        Log.d("ClientActivity", "C: Sending command.");
                        PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
                                    .getOutputStream())), true);
                            // where you issue the commands
                            out.println("Hey Server!");
                            Log.d("ClientActivity", "C: Sent.");
                    } catch (Exception e) {
                        Log.e("ClientActivity", "S: Error", e);
                    }
                }
                socket.close();
                Log.d("ClientActivity", "C: Closed.");
            } catch (Exception e) {
                Log.e("ClientActivity", "C: Error", e);
                connected = false;
            }
        }
    }
}   

服务器代码

import java.io.*;
import java.net.*;

/**
 * Simple server using Java Sockets.
 * @author Jonathan Engelsma (http://www.cis.gvsu.edu/~engelsma)
 *
 */
public class Server {

/**
 * @param args
 */
public static void main(String[] args) {

    try {
        // First we create a server socket and bind it to port 9999.
        ServerSocket myServerSocket = new ServerSocket(9999);


        // wait for an incoming connection... 
        System.out.println("Server is waiting for an incoming connection on host=" 
                + InetAddress.getLocalHost().getCanonicalHostName() 
                + " port=" + myServerSocket.getLocalPort());
        Socket skt = myServerSocket.accept();

        // ok, got a connection.  Let's use java.io.* niceties to read and write from the connection.
        BufferedReader myInput = new BufferedReader(new InputStreamReader(skt.getInputStream()));
        PrintStream myOutput = new PrintStream(skt.getOutputStream());  

        // attempt to read input from the stream.
        String buf = myInput.readLine();

        // if we got input, print it out and write a message back to the remote client..
        if (buf != null) {
            System.out.println("Server read: [" + buf + "]");
            myOutput.print("got it");
        }

        // close the connection.
        skt.close();
        System.out.println("Server is exiting");

    } catch (IOException ex) {
        ex.printStackTrace();
        System.out.println("Whoops, something bad happened!  I'm outta here.");
    }



}

}

2 个答案:

答案 0 :(得分:0)

您使用的是

吗?
<uses-permission android:name="android.permission.INTERNET" />

在Android Manifest中?这可能会导致你的问题。

答案 1 :(得分:0)

如果您使用的是ICS或JB,那么您可能无法在主要活动中打开网络连接。您将收到有关网络权限的不透明错误消息。

我无法将我的答案重新发布到另一个非常相似的StackOverflow问题(主持人认为它是垃圾邮件),但你可以CHECK IT OUT HERE

我在那里使用asynctask发布了一个功能性的发送和接收套接字连接器客户端。