0

Здравствуйте имею проблему написан сервер на java и необходим клиент на Android, проблема заключается в том, что приложение завершается после того как кто-нибудь подключиться, отправит сообщение или же отправится сообщение с приложения, ошибка [Ошибка в потоке[1]

К сожалению мне не хватает навыков и знаний чтобы исправить ошибку поэтому прошу помочь разобраться в чем я налажал

Код сервера

package ru.testing.chat.server;

import ru.testing.chat.network.TCPConnection;
import ru.testing.chat.network.TCPConnectionListener;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.ArrayList;

public class ChatServer implements TCPConnectionListener {
  public static void main(String[] args){
   new ChatServer();
}
private final ArrayList <TCPConnection> connections = new ArrayList<>();
private ChatServer(){
    System.out.println("Server running!");
    try {
        ServerSocket serverSocket = new ServerSocket(8188);
        while (true){
            try {
                new TCPConnection(this, serverSocket.accept());
            } catch (IOException e){
                System.out.println("TCPConnection Exception "+e);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

@Override
public synchronized void onConnectionReady(TCPConnection tcpConnection) {
    connections.add(tcpConnection);
    sendAllConnect("Client Connected"+ tcpConnection);
}

@Override
public synchronized void onReceiveString(TCPConnection tcpConnection, String value) {
    sendAllConnect(value);
}

@Override
public synchronized void onDisconnect(TCPConnection tcpConnection) {
    connections.remove(tcpConnection);
    sendAllConnect("TCPConnection Disconnected");
}

@Override
public synchronized void onException(TCPConnection tcpConnection, Exception e) {
    System.out.println("TCPConnection "+e);
}

private void sendAllConnect(String msg){
    System.out.println(msg);
    final int cnt = connections.size();
    for(int i = 0; i<cnt; i++){
        connections.get(i).sendMessage(msg);
    }
}

}

Класс который делает TCP соединение

package ru.testing.chat.network;

import java.io.*;
import java.net.Socket;
import java.nio.charset.Charset;

public class TCPConnection {
private final Socket socket;
private final Thread rxThread;
private final TCPConnectionListener eventListener;
private final BufferedReader in;
private final BufferedWriter out;

public TCPConnection(TCPConnectionListener eventListener, String ipAddress,int Port) throws IOException{
    this(eventListener,new Socket(ipAddress,Port));
}
public TCPConnection(TCPConnectionListener eventListener, Socket socket) throws IOException{
    this.eventListener = eventListener;
    this.socket = socket;
    in = new BufferedReader(new InputStreamReader( socket.getInputStream(), Charset.forName("UTF-8")));
    out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),Charset.forName("UTF-8")));
    rxThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try{
                eventListener.onConnectionReady(TCPConnection.this);
                while(!rxThread.isInterrupted())
                {
                    String msg = in.readLine();
                    eventListener.onReceiveString(TCPConnection.this,msg);
                }
            }
            catch (IOException e){
                eventListener.onException(TCPConnection.this,e);
            }
            finally {
                eventListener.onDisconnect(TCPConnection.this);
            }
        }
    });
    rxThread.start();
}
public synchronized void sendMessage(String msg){
    try {
        out.write(msg + "\r\n");
        out.flush();
    } catch (IOException e) {
        eventListener.onException(TCPConnection.this,e);
        Disconnect();
    }
}
public synchronized void Disconnect(){
    rxThread.interrupt();
    try {
        socket.close();
    } catch (IOException e) {
        eventListener.onException(TCPConnection.this, e);
    }
}
@Override
public String toString(){
    return "TCPConnection :" + socket.getInetAddress() + " :"+socket.getPort();
}

}

Клиент на андройд

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

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class MainActivity extends AppCompatActivity implements TCPConnectionListener {
private TextView mLog;
private EditText mInput;
private EditText mNickname;
private Button mSend;
private TCPConnection tcpConnection;
private String IP_ADDRESS="192.168.1.40";
private int PORT=8188;
private CharSequence Logs="";

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

    mLog=(TextView)findViewById(R.id.Logs);
    mInput=(EditText)findViewById(R.id.Input);
    mNickname=(EditText)findViewById(R.id.NickName);
    mSend=(Button)findViewById(R.id.SendMessage);

    Thread sThread = new Thread(new Runnable() {
        @Override
        public void run() {
            ChatConnection();
        }
    });
    sThread.start();
    mSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            tcpConnection.sendMessage(mNickname.getText()+": "+mInput.getText());

        }
    });
}
public void ChatConnection(){
    InetAddress ipAdress=null;
    try {
         ipAdress=InetAddress.getByName(IP_ADDRESS);
    } catch (UnknownHostException e) {
        System.out.println(e);
    }
    try{
        tcpConnection = new TCPConnection(this,ipAdress,PORT);
    }catch (IOException e){
        this.onException(tcpConnection,e);
    }
}

@Override
public void onConnectionReady(TCPConnection tcpConnection) {
    printMessage("Client is in Online");
}

@Override
public void onReceiveString(TCPConnection tcpConnection, String value) {
    printMessage(value);
}

@Override
public void onDisconnect(TCPConnection tcpConnection) {
    printMessage("Client is offline");
}

@Override
public void onException(TCPConnection tcpConnection, Exception e) {
    printMessage("TCPConnection error: "+e);
}
private synchronized  void printMessage(String mes){
    Thread mesThread= new Thread(new Runnable() {
        @Override
        public void run() {
            Logs=mLog.getText();
            mLog.setText(Logs+"\n"+mNickname.getText()+": "+mInput.getText());

        }
    });
    mesThread.start();
}

Ну и тот же TCPConnetion для android

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.charset.Charset;

public class TCPConnection {
private final Socket socket;
private final Thread rxThread;
private final TCPConnectionListener eventListener;
private final BufferedReader in;
private final BufferedWriter out;

public TCPConnection(TCPConnectionListener eventListener, InetAddress ipAddress,int Port) throws IOException{
    this(eventListener,new Socket(ipAddress,Port));
}
public TCPConnection(final TCPConnectionListener eventListener, Socket socket) throws IOException{
    this.eventListener = eventListener;
    this.socket = socket;
    in = new BufferedReader(new InputStreamReader( socket.getInputStream(), Charset.forName("UTF-8")));
    out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),Charset.forName("UTF-8")));
    rxThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try{
                eventListener.onConnectionReady(TCPConnection.this);
                while(!rxThread.isInterrupted())
                {
                    String msg = in.readLine();
                    eventListener.onReceiveString(TCPConnection.this,msg);
                }
            }
            catch (IOException e){
                eventListener.onException(TCPConnection.this,e);
            }
            finally {
                eventListener.onDisconnect(TCPConnection.this);
            }
        }
    });
    rxThread.start();
}
public synchronized void sendMessage(String msg){
    try {
        out.write(msg + "\r\n");
        out.flush();
    } catch (IOException e) {
        eventListener.onException(TCPConnection.this,e);
        Disconnect();
    }
}
public synchronized void Disconnect(){
    rxThread.interrupt();
    try {
        socket.close();
    } catch (IOException e) {
        eventListener.onException(TCPConnection.this, e);
    }
}
@Override
public String toString(){
    return "TCPConnection :" + socket.getInetAddress() + " :"+socket.getPort();
}

}

5
  • mLog.setText(Logs+"\n"+mNickname.getText()+": "+mInput.getText()); - для работы с view не в основном потоке используй, например, Handler 5 фев 2019 в 9:41
  • А в чем различие между Handler и обычным потоком, к сожалению читая сейчас разницы не вижу, можете ли вы пояснить
    – Igoko
    5 фев 2019 в 10:10
  • Нельзя из не-UI потока обращаться к UI элементам. В этом суть вашего креша и это пытается вам донести @AndreyMihalev 5 фев 2019 в 10:17
  • Понятно, сейчас попробую, ещё раз
    – Igoko
    5 фев 2019 в 10:25
  • Прошлый мой комментарий был не верен, и мне говорили верно ошибка была именно из-за того куска кода
    – Igoko
    5 фев 2019 в 14:06

1 ответ 1

1

Итак методом проб и ошибок, я нашёл свой костыль, я начал вызывать отдельной процедурой соединение и отправку, и чтобы бесконечно не спамить подключения я создал "Конструктор" постоянного соединения, и ссылаясь на него отправляю сообщения на сервер. ниже видоизмененный кусок кода для клиента на андройд

mSend=(Button)findViewById(R.id.SendMessage);
mConnect=(Button)findViewById(R.id.Connect);
mSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Sending();
        }
    });
 mConnect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Connecting();
        }
    });

}
public void Sending(){
    Thread sThread = new Thread(new Runnable() {
        @Override
        public void run() {
            TtcpConnection.sendMessage(mNickname.getText()+": "+mInput.getText());


        }
    });
    sThread.start();
}

public void Connecting(){
    Thread sThread = new Thread(new Runnable() {
        @Override
        public void run() {
            TtcpConnection=ChatConnection();

        }
    });
    sThread.start();
}
public TCPConnection ChatConnection(){
    TCPConnection tcpConnection=null;
    InetAddress ipAdress=null;
    try {
         ipAdress=InetAddress.getByName(IP_ADDRESS);
    } catch (UnknownHostException e) {
        System.out.println(e);
    }
    try{
        tcpConnection = new TCPConnection(this,ipAdress,PORT);
    }catch (IOException e){
        this.onException(tcpConnection,e);
    }
    return tcpConnection;
}

P.S. Когда смогу понять как использовать Handler, отправлю и другой кусок где всё записывается в TextView

UPD: Вот рабочий вариант клиента, хотя вероятнее всего сделан из гипсокартона)

public class MainActivity extends AppCompatActivity implements TCPConnectionListener {
private TextView mLog;
private EditText mInput;
private EditText mNickname;
private Button mSend;
private Handler mHandler;
private Button mConnect;
public TCPConnection TtcpConnection;
private String IP_ADDRESS="192.168.1.40";
private int PORT=8188;
private String Logs="";

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

    mLog=(TextView)findViewById(R.id.Logs);
    mInput=(EditText)findViewById(R.id.Input);
    mNickname=(EditText)findViewById(R.id.NickName);
    mSend=(Button)findViewById(R.id.SendMessage);
    mConnect=(Button)findViewById(R.id.Connect);
    mSend.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Sending();
        }
    });
    mConnect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Connecting();
        }
    });
    mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Log.d("LOG-TAG","Всё Отлично");
            CharSequence text = mLog.getText()+Logs;
            if(msg.what==2) mLog.setText(text+"\n");
        }
    };


}
public void Sending(){
    Thread sThread = new Thread(new Runnable() {
        @Override
        public void run() {
            TtcpConnection.sendMessage(mNickname.getText()+": "+mInput.getText());


        }
    });
    sThread.start();
}

public void Connecting(){
    Thread sThread = new Thread(new Runnable() {
        @Override
        public void run() {
            TtcpConnection=ChatConnection();
            onConnectionReady(TtcpConnection);

        }
    });
    sThread.start();
}
public TCPConnection ChatConnection(){
    TCPConnection tcpConnection=null;
    InetAddress ipAdress=null;
    try {
         ipAdress=InetAddress.getByName(IP_ADDRESS);
    } catch (UnknownHostException e) {
        System.out.println(e);
    }
    try{
        tcpConnection = new TCPConnection(this,ipAdress,PORT);
    }catch (IOException e){
        this.onException(tcpConnection,e);
    }
    return tcpConnection;
}

@Override
public void onConnectionReady(TCPConnection tcpConnection) {
    printMessage("Client is in Online");
}

@Override
public void onReceiveString(TCPConnection tcpConnection, String value) {
    printMessage(value);
}

@Override
public void onDisconnect(TCPConnection tcpConnection) {
    printMessage("Client is offline");
}

@Override
public void onException(TCPConnection tcpConnection, Exception e) {
    printMessage("TCPConnection error: "+e);
}
public synchronized void printMessage(String mes){
    Logs = mes;
    mHandler.sendEmptyMessage(2);

}

}

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.