Skip to content

Instantly share code, notes, and snippets.

@lb5160482
Created January 15, 2018 21:59
Show Gist options
  • Save lb5160482/7ed89f0ef1ab4b49cdcf3cf93f936bff to your computer and use it in GitHub Desktop.
Save lb5160482/7ed89f0ef1ab4b49cdcf3cf93f936bff to your computer and use it in GitHub Desktop.
TCP server JAVA Android
package com.dreamworldvision.trash;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import android.app.Activity;
import android.nfc.Tag;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;
public class MainActivity extends Activity {
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
private TextView text;
public static final int SERVERPORT = 5556;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_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();
}
}
class ServerThread implements Runnable {
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SERVERPORT);
} catch (IOException e) {
e.printStackTrace();
}
try {
socket = serverSocket.accept();
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class CommunicationThread implements Runnable {
private Socket clientSocket;
private BufferedReader input;
private PrintWriter out;
String TAG = "MyService";
public CommunicationThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
this.out = new PrintWriter(this.clientSocket.getOutputStream(), true);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
int i = 10;
while (!Thread.currentThread().isInterrupted()) {
try {
Log.d(TAG, "before read");
String read = input.readLine();
Log.d(TAG, "before write");
Log.d(TAG, read);
updateConversationHandler.post(new updateUIThread(read));
out.println(i + " from server");
i++;
Log.d(TAG, "after write");
} 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");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment