client
class ClientThread implements Runnable {
@Override
public void run() {
try {
socket = new Socket();
InetSocketAddress socketAddress = new InetSocketAddress(SERVER_IP, SERVERPORT);
socket.connect(socketAddress);
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (UnknownHostException e1) {
e1.printStackTrace();
}catch (IOException e1) {
e1.printStackTrace();
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
final String read1 = input.readLine();
updateConversationHandler.post(new updateUIThread(read1));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIThread implements Runnable {
private String msg;
public updateUIThread(String str) {
this.msg = str;
}
@SuppressLint("SdCardPath")
@Override
public void run() {
text1.setText(text1.getText().toString()+"Server Says: "+ msg + "\n");
}
}
server
class ServerThread implements Runnable {
public void run() {
socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
while (!Thread.currentThread().isInterrupted()) {
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
}catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
new Thread(new ServerThread()).start();
}
}
public void run() {
while (!Thread.currentThread().isInterrupted()) {
try {
final String read1 = input.readLine();
updateConversationHandler.post(new updateUIThread(read1));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
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");
}
}