I am trying to build a simple TCP Server for my android app. Here is my code:
public class TCPServer extends Thread{
int port;
String result;
ServerSocket serverClient;
TextView tv5;
MainActivity at;
public TCPServer(int newPort,MainActivity at) {
this.port=newPort;
this.at=at;
try{
serverClient=new ServerSocket(port);
}catch(IOException e) {
e.printStackTrace();
}
}
public void run() {
tv5=(TextView)at.findViewById(R.id.textView5);
Socket s;
try {
while (true) {
s= serverClient.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(s.getInputStream()));
this.result = inFromClient.readLine();
tv5.setText(this.result);
s.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}
public String getResult() {
return this.result;
}
public void setResult(String s){
this.result=s;
}
public void TCPclose(){
try {
serverClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And it calls when someone press the button:
receive_data.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
receiveResult.start();
tv5.setText(receiveResult.getResult());
}
});
But it seem that it can reach the line:
s= serverClient.accept();
It gets stuck before that line. I think that maybe there is no client connect to server so i try to write code for server to wait for the client but it does not work. Here is my attemp:
public class TCPServer extends Thread{
int port;
String result;
ServerSocket serverClient;
TextView tv5;
MainActivity at;
public TCPServer(int newPort,MainActivity at) {
this.port=newPort;
this.at=at;
try{
serverClient=new ServerSocket(port);
}catch(IOException e) {
e.printStackTrace();
}
}
public void run() {
tv5=(TextView)at.findViewById(R.id.textView5);
Socket s;
try {
while (true) {
Thread.sleep(10)
s= serverClient.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(s.getInputStream()));
this.result = inFromClient.readLine();
tv5.setText(this.result);
s.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}
public String getResult() {
return this.result;
}
public void setResult(String s){
this.result=s;
}
public void TCPclose(){
try {
serverClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
But it does not work. Can someone show me where am i wrong. Thank you. Sorry for my bad English.
Related
The idea here is to make a socket connection over the local network, send some data, and close the connection immediately. The only thing that should remain running is the serversocket. So far, everything works as expected except one thing:
When the activity that starts the serversocket gets closed with the back button, and then reopened, the data being sent from the client no longer makes it to the serversocket.
DMActivity:
public class DMActivity extends AppCompatActivity {
String ipAddress;
boolean dmListenRunning = false;
DMListen dmListen = new DMListen();
Thread dmListenThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dm);
if (!(dmListenRunning)) {
dmListenThread = new Thread(dmListen);
dmListenRunning = true;
dmListenThread.start();
}
}
#Override
public void onBackPressed()
{
try {
dmListen.KillThread(true);
dmListenThread.interrupt();
}
catch (Exception e)
{
Log.i("LOG", e.toString());
}
finish();
}
}
DMListen:
public class DMListen implements Runnable {
ServerSocket serverSocket;
boolean started = false;
boolean closeSockets = false;
boolean killed = false;
public void run() {
ReceivePlayerData();
}
public void ReceivePlayerData() {
try {
while (!(Thread.interrupted())) {
if (!(started)) {
int port = 8080;
serverSocket = new ServerSocket(port);
started = true;
}
Socket clientSocket = serverSocket.accept();
DataInputStream dataIn = new DataInputStream(clientSocket.getInputStream());
String name;
int init;
name = dataIn.readUTF();
init = dataIn.readInt();
dataIn.close();
clientSocket.close();
}
}
catch (Exception e) {
Log.i("LOG", e.toString();
}
if(killed)
{
try {
serverSocket.close();
if (Thread.currentThread().isInterrupted())
{
try {
Thread.currentThread().join();
}
catch (Exception e)
{
Log.i("LOG", e.toString());
}
}
}
catch(IOException e)
{
Log.i("LOG", e.toString());
}
}
}
public void KillThread(boolean k)
{
boolean killed = k;
}
}
PlayerActivity:
public class PlayerActivity extends AppCompatActivity {
EditText hostIPBox;
Button submit;
String hostIPString;
InetAddress hostIP;
boolean denied = false;
boolean started = false;
PlayerConnect playerConnect;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
hostIPBox = (EditText) findViewById(R.id.ipaddress);
hostIPBox.setRawInputType(Configuration.KEYBOARD_12KEY);
hostIPBox.setSingleLine();
submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
hostIPString = hostIPBox.getText().toString();
try {
if (!(hostIPString.equals(""))) {
hostIP = InetAddress.getByName(hostIPString);
if(!(started)) {
playerConnect = new PlayerConnect();
playerConnect.SetHostIP(hostIP);
denied = playerConnect.GetDenied();
started = true;
}
else {
playerConnect.SetHostIP(hostIP);
denied = playerConnect.GetDenied();
}
if (denied)
{
started = false;
}
else
{
new Thread(playerConnect).start();
}
}
}
catch (Exception e) {
Log.e("LOG", e.toString());
}
}
});
}
}
PlayerConnect:
public class PlayerConnect implements Runnable {
InetAddress hostIP;
boolean closeSockets = false;
boolean denied = false;
public void run() {
SendPlayerData(hostIP, playerName, playerInitiative);
}
private void SendPlayerData(InetAddress IP, String name, int init) {
try {
int port = 8080;
Socket socket = new Socket();
socket.connect(new InetSocketAddress(IP, port), 3000);
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
if (socket.isConnected())
{
output.writeUTF(name);
output.writeInt(init);
output.close();
socket.close();
}
if (closeSockets) {
output.close();
socket.close();
closeSockets = false;
}
}
catch (Exception e) {
denied = true;
Log.i("LOG", e.printStackTrace());
}
}
public void SetHostIP(InetAddress host)
{
hostIP = host;
}
public boolean GetDenied()
{
return denied;
}
}
You should use Service to handle socket connection. You won't have problems with Activity lifecycle.
I have a server and client program, which Client can send message to server. So, how to make the Server that can send back any response message to client?
This is the Server Code:
public class MainActivity extends Activity {
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
private TextView text;
public static final int SERVERPORT = 6000;
#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();
}
while (!Thread.currentThread().isInterrupted()) {
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;
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 {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} 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");
}
}
}
And this is the Client code:
public class MainActivity extends Activity {
private Socket socket;
private static final int SERVERPORT = 6000;
private static final String SERVER_IP = "192.168.177.102";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
You need to use the socket Stream same way as the client..
you can do in the run method
PrintWriter pw;
pw = new PrintWriter(new OutputStreamWriter(soc.getOutputStream()));
String read = input.readLine();
pw.println(read);
pw.flush();
Using this great tutorial by the Java Code Geeks, I am easily able to create a client activity that sends data via TCP to a server's port 4000 using the following code:
public class Client extends Activity {
private Socket socket;
private static final int SERVERPORT = 5000;
private static final String SERVER_IP = "10.0.2.2";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
Then using their other snippet for the server activity I can catch messages using TCP on that port:
public class Server extends Activity {
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
private TextView text;
public static final int SERVERPORT = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.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();
}
while (!Thread.currentThread().isInterrupted()) {
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;
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 {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} 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");
}
}
}
My question is how can I make it so these 2 can communicate back and forth?
Android -> Server(4000) -> Android(4001)?
In other words how can I make my app help the device act as both the client (sending out data to another device on port 4000) and the server (listening for data on port 4001) at the same time?
On the Server side change the port to 5000 (same as Client) instead of 6000:
And you need to update the following class because you don't want to create a new socket, you should use the one already created (in the Client part).
NB: the socket given as an argument to CommunicationThread is the socket that you supposedly already created (Client part).
class ServerThread implements Runnable {
public void run() {
while (!Thread.currentThread().isInterrupted()) {
CommunicationThread commThread = new CommunicationThread(socket);
new Thread(commThread).start();
}
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm working on a Android application that uses TCP/IP. I can easily send a message to the server to the client but I can figure out how to send a message from the server to the client. I've looked around and can't find a answer. Is it just some kind of output writer?
Public class MainActivity extends Activity {
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
private TextView text;
public static final int SERVERPORT = 6000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.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();
}
while (!Thread.currentThread().isInterrupted()) {
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;
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 {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} 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("");
if (msg != null){
text.setText(text.getText().toString()+"binary message sent: "+ msg + "\n");
String[] list_bin = new String[list_command.length];
for(int i=0 ; i<list_command.length; i++){
list_bin[i] = Integer.toBinaryString(i);
if ( list_bin[i] == null ? msg == null : list_bin[i].equals(msg)){
msg = list_command[i];
}
}
text.setText(text.getText().toString()+"Found input : "+ msg + "\n");
}
}
}
How do I have the server send a message to the client?
The simplest way is to use OutputStreamWriter on clientSocket.getOutputStream, and write to it from a separate thread.
I've built a TCP server and now I would like to turn it into a jar so I can use it in many different app. So basically later on I'd like to just include it in other projects. if it was just a list of functions I could figure it out but it's not I'm so I'm not sure. I thought about making it all just one function but it wouldn't run, when I called the function the app would just fail.
Also I hope other people can find this server code useful for their own projects
public class MainActivity extends Activity {
private ServerSocket serverSocket;
Handler updateConversationHandler;
Thread serverThread = null;
public String serverIP = "127.0.0.1";
private InetAddress serverAddr;
public static final int SERVERPORT = 4444;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
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();
}
while (!Thread.currentThread().isInterrupted()) {
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;
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 {
String read = input.readLine();
updateConversationHandler.post(new updateUIThread(read));
} catch (IOException e) {
e.printStackTrace();
}
}
}
}