Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android套接字失败_Android_Sockets_Client - Fatal编程技术网

Android套接字失败

Android套接字失败,android,sockets,client,Android,Sockets,Client,这是我的服务器代码 using System; using System.IO; using System.Net.Sockets; using System.Text; using System.Collections; using System.Threading; public class SynchronousSocketListener { private const int portNum = 4444;

这是我的服务器代码

 using System;
    using System.IO;
    using System.Net.Sockets;
    using System.Text;
    using System.Collections;
    using System.Threading;

    public class SynchronousSocketListener
    {

    private const int portNum = 4444;
    private static ArrayList ClientSockets;
    private static bool ContinueReclaim = true;
    private static Thread ThreadReclaim;

    public static void StartListening()
    {

        ClientSockets = new ArrayList();

        ThreadReclaim = new Thread(new ThreadStart(Reclaim));
        ThreadReclaim.Start();

        TcpListener listener = new TcpListener(portNum);
        try
        {
            listener.Start();

            int TestingCycle = 3;
            int ClientNbr = 0;

            // Start listening for connections.
            Console.WriteLine("Waiting for a connection...");
            while (TestingCycle > 0)
            {

                TcpClient handler = listener.AcceptTcpClient();

                if (handler != null)
                {
                    Console.WriteLine("Client#{0} accepted!", ++ClientNbr);
                    // An incoming connection needs to be processed.
                    lock (ClientSockets.SyncRoot)
                    {
                        int i = ClientSockets.Add(new ClientHandler(handler));
                        ((ClientHandler)ClientSockets[i]).Start();
                        Console.WriteLine("Added sock {0}", i);
                    }
                    --TestingCycle;
                }
                else
                    break;
            }
            listener.Stop();

            ContinueReclaim = false;
            ThreadReclaim.Join();

            foreach (Object Client in ClientSockets)
            {
                ((ClientHandler)Client).Stop();
            }

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }

        Console.WriteLine("\nHit enter to continue...");
        Console.Read();

    }

    private static void Reclaim()
    {
        while (ContinueReclaim)
        {
            lock (ClientSockets.SyncRoot)
            {
                for (int x = ClientSockets.Count - 1; x >= 0; x--)
                {
                    Object Client = ClientSockets[x];
                    if (!((ClientHandler)Client).Alive)
                    {
                        ClientSockets.Remove(Client);
                        Console.WriteLine("A client left");
                    }
                }
            }
            Thread.Sleep(200);
        }
    }


    public static int Main(String[] args)
    {
        while (true)
        {
            StartListening();
        }
        return 0;
    }
}

class ClientHandler
{

    TcpClient ClientSocket;
    bool ContinueProcess = false;
    Thread ClientThread;

    public ClientHandler(TcpClient ClientSocket)
    {
        this.ClientSocket = ClientSocket;
    }

    public void Start()
    {
        ContinueProcess = true;
        ClientThread = new Thread(new ThreadStart(Process));
        ClientThread.Start();
    }

    private void Process()
    {

        // Incoming data from the client.
        string data = null;

        // Data buffer for incoming data.
        byte[] bytes;

        if (ClientSocket != null)
        {
            NetworkStream networkStream = ClientSocket.GetStream();
            ClientSocket.ReceiveTimeout = 100; // 1000 miliseconds

            while (ContinueProcess)
            {
                bytes = new byte[ClientSocket.ReceiveBufferSize];
                try
                {

                    int BytesRead = networkStream.Read(bytes, 0, (int)ClientSocket.ReceiveBufferSize);
                    //BytesRead--;
                    if (BytesRead > 0)
                    {
                        Console.WriteLine("Bytes Read - Debugger " + BytesRead);
                        data = Encoding.ASCII.GetString(bytes, 0, BytesRead);

                        // Show the data on the console.
                        Console.WriteLine("Text received : {0}", data);

                        // Echo the data back to the client.
                        byte[] sendBytes = Encoding.ASCII.GetBytes("I rec ya abbas");
                        networkStream.Write(sendBytes, 0, sendBytes.Length);

                        if (data == "quit") break;

                    }
                }
                catch (IOException) { } // Timeout
                catch (SocketException)
                {
                    Console.WriteLine("Conection is broken!");
                    break;
                }
                Thread.Sleep(200);
            } // while ( ContinueProcess )
            networkStream.Close();
            ClientSocket.Close();
        }
    }  // Process()

    public void Stop()
    {
        ContinueProcess = false;
        if (ClientThread != null && ClientThread.IsAlive)
            ClientThread.Join();
    }

    public bool Alive
    {
        get
        {
            return (ClientThread != null && ClientThread.IsAlive);
        }
    }

} // class ClientHandler 
这是我的客户代码:

package com.example.socketclient;


import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.BufferedWriter; 
import java.io.IOException; 
import java.io.InputStream;
import java.io.OutputStreamWriter; 
import java.io.InputStreamReader;
import java.io.PrintWriter; 
import java.net.InetAddress; 
import java.net.Socket; 
import java.net.UnknownHostException; 
import android.util.Log; 

public class SocketCode extends Activity {

    public TextView txt;
    protected SocketCore Conn;
    public Button b;
    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_socket_code);
        b = (Button)findViewById(R.id.button1);
        txt = (TextView)findViewById(R.id.textView1);
        Conn = new SocketCore(this,txt);
        b.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                Conn.execute();

            }
        });






    }

}
插座芯

package com.example.socketclient;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.app.ProgressDialog;

import android.content.Context;

import android.os.AsyncTask;
import android.os.SystemClock;

import android.os.Bundle;

import android.util.Log;

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;


class SocketCore extends AsyncTask<Context, Integer, String>
{
    String text = "";
    String finalText = "";
    private Context ctx;
    ProgressDialog dialog;
    TextView Msg;
    Socket socket;
    public SocketCore(Context applicationContext,TextView Change) 
    {
        // TODO Auto-generated constructor stub
        ctx = applicationContext;
        dialog = new ProgressDialog(applicationContext);
        Msg = Change;
    }

    @Override
    protected String doInBackground(Context... arg0) {
        // TODO Auto-generated method stub

         try { 
                InetAddress serverAddr = InetAddress.getByName("192.168.0.150"); 
                Log.d("TCP", "C: Connecting....");

                socket = new Socket(serverAddr,4444); 
               // Log.d("TCP", "C: I dunno ...");
                String message = "Hello Server .. This is the android client talking to you .. First we are testing Server Crashing";

                PrintWriter out = null;
                BufferedReader in = null;

                try { 
                    Log.d("TCP", "C: Sending: '" + message + "'"); 
                    out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true); 
                    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));                
                   //serverReturnString = System.Text.Encoding.ASCII.GetString(response, 0, bytes);

                    out.println("quit");
                   //out.print("h");
                    while ((text = in.readLine()) != null) {
                        finalText += text;
                      if(text=="quit")
                      {
                          socket.close();
                      }
                        Log.d("TCP", "C: Done."+finalText);
                        }

               //   Msg.setText("LOLZ");
                    Log.d("TCP", "C: Sent."); 



                } catch(Exception e) { 
                    Log.e("TCP", "S: Error", e); 
                } /*finally { 
                    socket.close(); 
                    Log.d("TCP", "S: Closed"); 
                } */

            }catch (UnknownHostException e) { 
                // TODO Auto-generated catch block 
                Log.e("TCP", "C: UnknownHostException", e); 
                e.printStackTrace(); 
            } catch (IOException e) { 
                // TODO Auto-generated catch block 
                Log.e("TCP", "C: IOException", e); 
                e.printStackTrace(); 
            }       
           //dialog.setMessage("Recieved: "+finalText);

        return "COMPLETE";
    }
    protected void onPostExecute(String x)
    {
        super.onPostExecute("Finished");
        dialog.dismiss();
        Msg.setText(finalText);

    }
    protected void onPreExecute()
    {dialog.setTitle("Initializing Connection");
    dialog.setMessage("Connecting");

        dialog.show();
    }

}
package com.example.socketclient;
导入java.io.BufferedReader;
导入java.io.BufferedWriter;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.io.OutputStreamWriter;
导入java.io.PrintWriter;
导入java.net.InetAddress;
导入java.net.Socket;
导入java.net.UnknownHostException;
导入android.app.Activity;
导入android.app.ProgressDialog;
导入android.content.Context;
导入android.os.AsyncTask;
导入android.os.SystemClock;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.view;
导入android.view.view.OnClickListener;
导入android.widget.TextView;
类SocketCore扩展了AsyncTask
{
字符串文本=”;
字符串finalText=“”;
私有上下文ctx;
进程对话;
文本视图消息;
插座;
公共SocketCore(上下文应用程序上下文、文本视图更改)
{
//TODO自动生成的构造函数存根
ctx=应用上下文;
dialog=新建进度对话框(applicationContext);
Msg=变化;
}
@凌驾
受保护的字符串doInBackground(上下文…arg0){
//TODO自动生成的方法存根
试试{
inetAddressServerAddr=InetAddress.getByName(“192.168.0.150”);
Log.d(“TCP”,“C:连接…”);
套接字=新套接字(serverAddr,4444);
//Log.d(“TCP”,“C:我不知道…”);
String message=“你好,服务器..这是android客户端正在与您交谈..首先我们正在测试服务器崩溃”;
PrintWriter out=null;
BufferedReader in=null;
试试{
Log.d(“TCP”,“C:发送:“+”消息+“”);
out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()),true);
in=新的BufferedReader(新的InputStreamReader(socket.getInputStream());
//serverReturnString=System.Text.Encoding.ASCII.GetString(响应,0,字节);
out.println(“退出”);
//打印输出(“h”);
而((text=in.readLine())!=null){
finalText+=文本;
如果(文本==“退出”)
{
socket.close();
}
Log.d(“TCP”,“C:完成”。+finalText);
}
//Msg.setText(“LOLZ”);
Log.d(“TCP”,“C:已发送”);
}捕获(例外e){
Log.e(“TCP”,“S:错误”,e);
}/*最后{
socket.close();
Log.d(“TCP”,“S:关闭”);
} */
}捕获(未知后异常e){
//TODO自动生成的捕捉块
Log.e(“TCP”,“C:未知后异常”,e);
e、 printStackTrace();
}捕获(IOE){
//TODO自动生成的捕捉块
Log.e(“TCP”,“C:IOException”,e);
e、 printStackTrace();
}       
//设置消息(“接收:+finalText”);
返回“完成”;
}
受保护的void onPostExecute(字符串x)
{
super.onPostExecute(“完成”);
dialog.dismise();
Msg.setText(finalText);
}
受保护的void onPreExecute()
{dialog.setTitle(“初始化连接”);
设置消息(“连接”);
dialog.show();
}
}
服务器可以从android手机读取信息,android客户端也可以从服务器获取信息。 问题在于,每当服务器检测到连接并开始接收文本并发送回复时。代码在此之后不接受更多连接

注:
我尝试使用C#client进行测试,它工作正常,因此客户端出现问题

您不能使用比AsyncTask更多的任务

最简单的方法是将
doInBackground()
中的代码移动到
Runnable
,然后在每次单击时启动一个新的
线程

例如:

private Runnable rSocketCore = new Runnable() {
    public void run() {
          //here goes your connection code
    }
};


    b.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
             new Thread(rSocketCore).start();
        }
注意:
如果要从线程到UI进行通信,还需要一个
处理程序


问候。

您不能多次执行AsynTask。。。在每次单击时创建新的SocketCore然后如何保持socket运行。。而且我不能在主线程上编写套接字代码,这就是我选择异步的原因