如何用Java实现服务器确认后客户端才能发送下一条信息。

提主已经能够用java实现服务端与客户端的聊天通信。关键代码如下:客户端publicclassserver{publicstaticvoidmain(String[]ar... 提主已经能够用java实现服务端与客户端的聊天通信。关键代码如下:
客户端
public class server {
public static void main(String[] args) {
new server().startServer();
}
public void startServer(){
try {
//服务器在9990端口监听客户端的连接
ServerSocket ss = new ServerSocket(9990);
System.out.println("server is listening...");
while(true){
//阻塞的accept方法,当一个客户端连接上,才会返回Socket对象
Socket s = ss.accept();
System.out.println("a client has connected!");
//开启线程处理通信
new CommunicateThread(s).start();
}
//读取客户端发过来的消息
String msg = null;
try {
while((msg = dis.readUTF()) != null){
System.out.println("client send msg :" + msg);
String replyMsg = "server reply : " + msg;
dos.writeUTF(replyMsg);
System.out.println("server reply msg :" + replyMsg);
}
客户端:
public void startClient(){
try {
//连接到服务器
Socket socket = new Socket("192.168.53.151", 9990);
DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
Scanner scanner = new Scanner(System.in);
String line = null;
listenServerReply(dis);
while((line = scanner.nextLine()) != null){//读取从键盘输入的一行
dos.writeUTF(line);//发给服务端
System.out.println("client send msg : " + line);

//监听服务端回复的消息
public void listenServerReply(final DataInputStream dis){
new Thread(){
public void run() {
super.run();
String line = null;
try {
while((line = dis.readUTF()) != null){
System.out.println("client receive msg from server: " + line);
}
} catch (IOException e) {
e.printStackTrace();
}

}
}.start();
}
想要实现服务器在收到一条信息后,回复ack确认之后,客户端才能发送下一条信息。
请问在此基础上如何让修改?
展开
 我来答
Mexico卡卡
2017-11-19 · TA获得超过1万个赞
知道大有可为答主
回答量:1.3万
采纳率:98%
帮助的人:1883万
展开全部
  1. Server代码

package com.javacodegeeks.android.androidsocketserver;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;
 
public class Server extends Activity
{
    private ServerSocket serverSocket;
    private Handler updateConversationHandler;
    private Thread serverThread = null;
    private TextView text;
    public static final int SERVERPORT = 6000;
 
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        text = (TextView) findViewById(R.id.text2);
 
        updateConversationHandler = new Handler();
 
        this.serverThread = new Thread(new ServerThread());
        this.serverThread.start();
 
    }
 
    @Override
    protected void onStop()
    {
        super.onStop();
        try
        {
            serverSocket.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
 
    private class ServerThread implements Runnable
    {
 
        public void run()
        {
            Socket socket = null;
            try
            {
                serverSocket = new ServerSocket(SERVERPORT);
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            while (!Thread.currentThread().isInterrupted())
            {
                try
                {
                    socket = serverSocket.accept(); // TODO
 
                    CommunicationThread commThread = new CommunicationThread(socket);
                    new Thread(commThread).start();
                }
                catch (IOException e)
                {
                    Log.i("liu", "socket.accept()失败");
 
                    e.printStackTrace();
                }
            }
        }
    }
 
    private class CommunicationThread implements Runnable
    {
        private Socket clientSocket;
        private BufferedReader input;
 
        public CommunicationThread(Socket clientSocket)
        {
            this.clientSocket = clientSocket;
 
            Log.i("liu", "获取到了client的Socket");
 
            try
            {
                this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream())); // TODO
            }
            catch (IOException e)
            {
                Log.i("liu", "input获取失败");
                e.printStackTrace();
            }
        }
 
        public void run()
        {
            while (!Thread.currentThread().isInterrupted())
            {
                try
                {
                    String read = input.readLine(); // TODO
                    Log.i("liu", read);
                    updateConversationHandler.post(new updateUIThread(read));
                }
                catch (IOException e)
                {
                    Log.i("liu", "input读取失败");
                    e.printStackTrace();
                }
            }
        }
    }
 
    private class updateUIThread implements Runnable
    {
        private String msg;
 
        public updateUIThread(String str)
        {
            this.msg = str;
        }
 
        @Override
        public void run()
        {
            text.setText(text.getText().toString() + "Client Says: " + msg + "\n");
        }
 
    }
 
}

2. Client代码:

package com.javacodegeeks.android.androidsocketclient;
 
import java.io.BufferedWriter;
import java.io.IOException;
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.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
 
public class Client extends Activity
{
    private Socket socket;
    private static final int SERVERPORT = 4000;
    private static final String SERVER_IP = "10.0.2.2";
 
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        new Thread(new ClientThread()).start();
    }
 
    public void onClick(View view)
    {
        try
        {
            EditText et = (EditText) findViewById(R.id.EditText01);
            String str = et.getText().toString();
 
            Log.i("liu", "点击按钮");
 
            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); // TODO
            out.println(str);
        }
        catch (Exception e)
        {
            Log.i("liu", "write失败");
            e.printStackTrace();
        }
    }
 
    class ClientThread implements Runnable
    {
 
        @Override
        public void run()
        {
            try
            {
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
                socket = new Socket(serverAddr, SERVERPORT);
            }
            catch (UnknownHostException e1)
            {
                e1.printStackTrace();
            }
            catch (IOException e1)
            {
                e1.printStackTrace();
            }
        }
    }
}
网易云信
2023-12-06 广告
很高兴能回答您的问题。以下是一段针对“一对一消息组件”的描述,字数在200字左右:该组件支持用户之间的私密交流,让沟通更加直接和高效。通过它,您可以向特定对象发送消息,并实时查看消息状态,包括对方是否已读或未读。同时,该组件还支持富文本消息... 点击进入详情页
本回答由网易云信提供
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式