服务器端套接字c#网络错误

时间:2014-02-24 15:39:47

标签: c# android serversocket

我非常擅长在visual studio中编写c#。我试图使用套接字从Android应用程序(客户端)向Windows应用程序(服务器端)发送消息。我不知道我是否应该能够在我拥有的无线网络中做到这一点,或者甚至是问题。我也可以选择和使用任何端口号,或者它必须是我必须从某处获取的特定号码?我将发布我的客户端和服务器代码,以及我的服务器端代码的输出。非常感谢任何帮助。

客户端:

public class MainActivity extends Activity { 
private EditText editTxt;

@Override 
public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_main); 
Button b = (Button)findViewById(R.id.button1);
editTxt = (EditText) findViewById(R.id.editText1);
final String str = editTxt.getText().toString();



b.setOnClickListener(new View.OnClickListener() {

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

    }
});
} 

private void connectSocket(String a){ 

new Thread( new Runnable() {
    @Override
    public void run() {

        try { 
            InetAddress serverAddr = InetAddress.getByName("10.5.5.117"); 
            Log.d("TCP", "C: Connecting..."); 
            Socket socket = new Socket(serverAddr, 5555); 

            String message = "1";

            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()));                

                out.println(message);

                String text = "";
                String finalText = "";
                while ((text = in.readLine()) != null) {
                    finalText += text;
                    }
                editTxt.setText(finalText);


                Log.d("TCP", "C: Sent."); 
                Log.d("TCP", "C: Done.");               

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

        } 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(); 
        }  
    }}).start();
    } 
}

服务器:

namespace WindowsSocketServer
{
public class serv
{
    public static void Main()
    {
        try
        {
            IPAddress ipAd = IPAddress.Parse("10.5.5.117");
            // use local m/c IP address, and 

            // use the same in the client


            // Initializes the Listener 
            TcpListener myList = new TcpListener(ipAd, 5555);

            // Start Listeneting at the specified port 
            myList.Start();

            Console.WriteLine("The server is running at port 5555...");
            Console.WriteLine("The local End point is  :" +
                              myList.LocalEndpoint);
            Console.WriteLine("Waiting for a connection.....");
        m:
            Socket s = myList.AcceptSocket();
            Console.WriteLine("Connection accepted from " + s.RemoteEndPoint);

            byte[] b = new byte[100];
            int k = s.Receive(b);

            char cc = ' ';
            string test = null;
            Console.WriteLine("Recieved...");
            for (int i = 0; i < k - 1; i++)
            {
                Console.Write(Convert.ToChar(b[i]));
                cc = Convert.ToChar(b[i]);
                test += cc.ToString();
            }

            switch (test)
            {
                case "1":
                    break;

            }

            ASCIIEncoding asen = new ASCIIEncoding();
            s.Send(asen.GetBytes("The string was recieved by the server."));
            Console.WriteLine("\nSent Acknowledgement");
            s.Close();


            // clean up 
            goto m;
            s.Close();
            myList.Stop();
            Console.ReadLine();

        }
        catch (Exception e)
        {
            Console.WriteLine("Error..... " + e.StackTrace); 
        }
    }

}
}

服务器输出:

The thread 'vshost.NotifyLoad' (0x21e8) has exited with code 0 (0x0).

The thread '<No Name>' (0x1d04) has exited with code 0 (0x0).

The thread 'vshost.LoadReference' (0x2448) has exited with code 0 (0x0).

'WindowsSocketServer.vshost.exe' (Managed (v4.0.30319)): Loaded     'C:\Projects\Offline\WindowsSocketServer\bin\Debug\WindowsSocketServer.exe', Symbols loaded.
'WindowsSocketServer.vshost.exe' (Managed (v4.0.30319)): Loaded   'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.Configuration\v4.0_4.0.0.0__b03f5f7f11d50    a3a\System.Configuration.dll', Skipped loading symbols. Module is optimized and the     debugger option 'Just My Code' is enabled.

Error.....    at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot,     SocketAddress socketAddress)
   at System.Net.Sockets.Socket.Bind(EndPoint localEP)
   at System.Net.Sockets.TcpListener.Start(Int32 backlog)
   at System.Net.Sockets.TcpListener.Start()
   at WindowsSocketServer.serv.Main() in 
C:\Projects\Offline\WindowsSocketServer\Program.cs:line 27

A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll

The thread 'vshost.RunParkingWindow' (0x1a5c) has exited with code 0 (0x0).

The thread '<No Name>' (0x1ba4) has exited with code 0 (0x0).

The program '[8828] WindowsSocketServer.vshost.exe: Managed (v4.0.30319)' has exited with code 0 (0x0).

1 个答案:

答案 0 :(得分:0)

您应该能够从SocketException获取有关问题的更多信息。 (描述,错误代码等)。我猜测它在Bind上打破可以简单地通过端口5555已被其他应用程序使用来解释(adb也许?)。通常只有一个应用程序可以侦听给定端口,因此请尝试不同的端口。您可以选择任何端口(&lt; 1024是保留端口,但任何高于65535的端口都是有效的)。只需更新客户端即可连接到新端口。

相关问题