套接字上的Java简单客户端服务器通信

时间:2016-02-08 23:20:31

标签: java sockets server client

我正在尝试为Android编写一个应用程序以连接到我的Java服务器并远程控制它(只需运行Media Player或者像这样)。 由于我从未写过任何套接字连接,我认为我应该从一些非常简单的东西开始 - 只需发送短消息。我的问题是我发送的第一条消息是好的。当我尝试发送另一条消息时,它没有来到服务器。 这是我的代码 Client.java

public class Client implements Runnable
{
    private Socket connection;
    private Long id;
    private InputStream is;
    public Boolean done;
    DataInputStream dIn ;

public Client(Socket conn, Long ids) throws IOException
{
    connection = conn;
    is = conn.getInputStream();
    id = ids;
    dIn = new DataInputStream(is);
    done = false;
}

public Socket getConnection()
{
    return connection;
}
public void setConnection(Socket connection)
{
    this.connection = connection;
}

public Long getId()
{
    return id;
}
public void setId(Long id)
{
    this.id = id;
}

@Override
public void run()
{
    String msg = "";
    while(!msg.equals("exit"))
    {
        try
        {
            if(is.available() >0)
            {
                int data =0;
                StringBuilder sb = new StringBuilder();
                while(data >=0)
                {
                    data = dIn.read();
                    char c = (char) data;
                    sb.append(c);
                }

                System.out.println(sb.toString());

            }

        }
        catch (IOException e) {
            done = true;
            e.printStackTrace();
        }
    }
}

}

现在Server.java

package tcp;

public class Server implements Runnable {

private ServerSocket serverSocket;
private final static int SERVER_PORT = 6879;
private ServerManager serverManager;
InputStreamReader inputStreamReader;
BufferedReader bufferedReader;

public Server(ServerManager serverManager)
{
    this.serverManager = serverManager;
}


@Override
public void run()
{
    try
    {
        serverSocket = new ServerSocket(SERVER_PORT);
        Log.log("Server został uruchomiony...");
        addConnection.run();

    }
    catch (IOException e) {
        Log.log(e.getMessage());
        Log.logStack(e);
    }
}


Runnable addConnection = () -> {
    Log.log("Uruchomiono wątek oczekiwania na połączenie");
    try {
        while(true)
        {
            Socket connection = serverSocket.accept();
            serverManager.addClient(connection);
            InetAddress ia = connection.getInetAddress();
            Log.log("Dodano klienta: "+ia.toString());
        }
    } catch (Exception e)
    {
        Log.log(e.getMessage());
        Log.logStack(e);
    }
};

}

和ServerManager.java

public class ServerManager implements Runnable
{
private Server server;
private HashMap<Long,Client> clients;
private Long lastId = Long.valueOf(0);
private Mutex clientsMutex = new Mutex();

@Override
public void run()
{
    clients = new HashMap<>();
    server = new Server(this);
    server.run();
}

public void addClient(Socket conn) throws IOException
{
    try
    {
        clientsMutex.acquire();
        ++lastId;
        Client cd = new Client(conn,lastId);
        clients.put(lastId, cd);
        Thread thread = new Thread(cd);
        thread.start();

    } catch (InterruptedException e)
    {
        Log.log(e.getMessage());
        Log.logStack(e);
    }
    finally
    {
        clientsMutex.release();
    }
}
}

当然还有客户代码:

public class SlimpleTextClientActivity extends Activity {

private Socket client;
private PrintWriter printwriter;
private EditText textField;
private Button button;
private String messsage;

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

    textField = (EditText) findViewById(R.id.editText1); // reference to the text field
    button = (Button) findViewById(R.id.button1); // reference to the send button
    establishConnection();
    // Button press event listener
    button.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            messsage = textField.getText().toString(); // get the text message on the text field
            textField.setText(""); // Reset the text field to blank
            SendMessage sendMessageTask = new SendMessage();
            sendMessageTask.execute();
        }
    });
}

private void establishConnection() {

    EstablishConnection est = new EstablishConnection();
    est.execute();
}

private class EstablishConnection extends AsyncTask<Void, Void, Void>
{

    @Override
    protected Void doInBackground(Void... params) {
        try {
            client = new Socket("192.168.0.12", 6879); // connect to the server

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
        return null;
    }
}

private class SendMessage extends AsyncTask<Void, Void, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        try {
            printwriter = new PrintWriter(client.getOutputStream(), true);
            printwriter.write(messsage); // write the message to output stream

            printwriter.flush();
            printwriter.close();


        }  catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.slimple_text_client, menu);
    return true;
}

}

1 个答案:

答案 0 :(得分:0)

您在发送单个邮件后关闭连接。因此,您需要打开一个新连接以发送新消息。或者在两端调整协议,以保持连接打开。