Здравствуйте имею проблему написан сервер на java и необходим клиент на Android, проблема заключается в том, что приложение завершается после того как кто-нибудь подключиться, отправит сообщение или же отправится сообщение с приложения, ошибка [
К сожалению мне не хватает навыков и знаний чтобы исправить ошибку поэтому прошу помочь разобраться в чем я налажал
Код сервера
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();
}
}
mLog.setText(Logs+"\n"+mNickname.getText()+": "+mInput.getText());
- для работы с view не в основном потоке используй, например,Handler