简单 java TCP 客户端

Simple java TCP client

我在 ESP8266 上有一个经过测试的服务器,带有环回和一个不发送消息的 tcp 客户端应用程序。我还在一台服务器上测试了它,它会告诉您是否有人连接并且它说它已连接。

"chat" textView 在我点击发送时显示消息。

例如:Client: message,但它不会将其发送到服务器以使其循环返回。

发送和接收消息需要修改什么?

客户端

package com.example.tinemasilo.researchgate_sockettut;

import android.app.Activity;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;

public class MainActivity extends Activity
{

static EditText serverIp,smessage;
static TextView chat;
static Button connectPhones,disconnectPhones,sent;
static String serverIpAddress = "",msg = "",str;
Handler handler = new Handler();
//static InetAddress serverAddr;
static Socket socket;
static DataOutputStream os;
//static DataInputStream in;
static BufferedReader in;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    chat = (TextView) findViewById(R.id.chat);
    serverIp = (EditText) findViewById(R.id.server_ip);
    smessage = (EditText) findViewById(R.id.smessage);

    sent = (Button) findViewById(R.id.sent_button);
    connectPhones = (Button) findViewById(R.id.connectPhones);
    disconnectPhones = (Button) findViewById(R.id.disconnectPhones);

    connectPhones.setEnabled(true);
    connectPhones.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            connectPhones.setEnabled(false);
            disconnectPhones.setEnabled(true);
            serverIpAddress = serverIp.getText().toString();
            //try
            //{
            //    InetAddress.getByName(serverIpAddress);
            //    serverAddr.getByName(serverIpAddress);
            //    socket = new Socket(serverAddr, 10000);
            //}
            // catch (IOException e)
            //{
            //}

            if (!serverIpAddress.equals(""))
            {
                Thread clientThread = new Thread(new ClientThread());
                clientThread.start();
            }

        }
    });

    sent.setOnClickListener(new View.OnClickListener()
     {
        public void onClick(View v)
        {
             Thread sentThread = new Thread(new sentMessage());
             sentThread.start();
         }
     });

      disconnectPhones.setEnabled(false);
      disconnectPhones.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v)
         {
            connectPhones.setEnabled(true);
            disconnectPhones.setEnabled(false);
                try
                {
                 socket.close();
                }
                catch (IOException e)
                {
                }
          }
      });
}

public class ClientThread implements Runnable
{
    public void run()
    {
        try
        {

            InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
            //serverAddr.getByName(serverIpAddress);
            socket = new Socket(serverAddr, 502);


            while(true)
            {
                //InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
                //serverAddr.getByName(serverIpAddress);
                //socket = new Socket(serverAddr, 10000);
                //in = new DataInputStream(socket.getInputStream());
                in = new BufferedReader( new InputStreamReader(socket.getInputStream()));
                String line = null;
                while ((line = in.readLine()) != null)
                {
                    msg = msg + "Server : " + line + "\n";
                    handler.post(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            chat.setText(msg);
                        }
                    });
                }
                in.close();
                Thread.sleep(100);
            }
        }
        catch (Exception e)
        {
        }
    }
}

class sentMessage implements Runnable
{
    @Override
    public void run()
    {
        try
        {

            InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
            //serverAddr.getByName(serverIpAddress);
            socket = new Socket(serverAddr, 502);

            os = new DataOutputStream(socket.getOutputStream());
            str = smessage.getText().toString();
            str = str + "\n";
            msg = msg + "Client : " + str;
            handler.post(new Runnable()
            {
                @Override
                public void run()
                {
                    chat.setText(msg);
                }
            });
            os.writeBytes(str);
            os.flush();
            os.close();
            }
        catch(IOException e)
        {
        }
    }
}
}

您正在尝试在 sentThread 中的同一端口上创建新的 Socket 连接。第一个连接是在 ClientThread class 中创建的,当您按下 sent 按钮时,您正在同一端口 502 上创建另一个 Socket 连接。我认为这是主要问题。

尝试使用 sentThread class 中现有的 Socket 连接。

class sentMessage implements Runnable
{
  @Override
  public void run()
  {
    try
    {

        //InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
        //serverAddr.getByName(serverIpAddress);
       // socket = new Socket(serverAddr, 502);

       // os = new DataOutputStream(socket.getOutputStream());
        str = smessage.getText().toString();
        str = str + "\n";
        msg = msg + "Client : " + str;
        handler.post(new Runnable()
        {
            @Override
            public void run()
            {
                chat.setText(msg);
            }
        });
        os.writeBytes(str);
        os.flush();
        //os.close();
        }
    catch(IOException e)
    {
    }
}
}

编辑: 如果您想发送多条消息,请不要关闭 DataOutputStream。从 sentMessage class 中删除 os.close();os = new DataOutputStream(socket.getOutputStream()); 行。 首次连接时初始化 os。然后每次你想发送消息时使用那个 os 实例。

ClientThread class 连接创建后初始化 os

   socket = new Socket(serverAddr, 502);
   os = new DataOutputStream(socket.getOutputStream());