Java中的简单TCP客户端服务器

时间:2016-05-25 14:51:55

标签: java android tcp

我通常不使用Java编程,但我决定编写一个简单的客户端 - 服务器应用程序,只是为了说明它是如何在Java中工作的。

当我通过eclipse运行服务器和客户端时 - 一切都很好,但是当我通过Android Studio在Android设备中运行客户端时 - 它不会连接到服务器。

两者都运行在同一个WIFI上。 服务器IP是pc的LAN ip。 服务器侦听端口32323,客户端连接到32323。

服务器:

public class Server
{
    private int port;
    private ServerSocket serverSocket;

    private Socket client;

    public Server(int port)
    {
        this.port = port;

        try
        {
            serverSocket = new ServerSocket(port);
        }
        catch (Exception exception) {}


        try
        {
            client = serverSocket.accept();
            System.out.println("logged in");
        }
        catch (Exception exception) {}

    }
}

客户端:

// The following line is written inside onCreate:
onlineClient = new OnlineClient(new byte[] {(byte) 192, (byte) 168, 1, 17}, 32323); 

public class OnlineClient
{
    private Socket socket;
    private PrintWriter writer;
    private BufferedReader reader;

    public OnlineClient(byte[] serverIP, int port)
    {
        try
        {
            socket = new Socket(Inet4Address.getByAddress(serverIP), port);
//          writer = new PrintWriter(socket.getOutputStream(), true);
//          reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));

//          socket.setTcpNoDelay(true);
        }
        catch (IOException e) {}

    }
}

0 个答案:

没有答案