I want to create a socket connection between my server and my client. My client should reconnect, after the connection timed out. For this, I try every 3 seconds to connect with my socket. And this works. But then, when I want to start reading, but then I get the error "socket closed". What could be the mistake?
Here is the error log (It's on pastebin, it doesn't formate here right):
http://pastebin.com/2t8zAvcx
But I try to get the IP from the socket before I start reading and this works...
Here is my reconnect method:
public void reconnect(){
new Thread(new Runnable() {
#Override
public void run() {
try{
try{
socket.close();
socket = null;
}catch (IOException e) {
}
socket = new Socket(BackgroundService.HOSTNAME, BackgroundService.PORT);
connected = true;
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
output.writeUTF(username);
output.flush();
}catch(UnknownHostException e){
connected = false;
}catch(IOException e){
connected = false;
}
}
}).start();
}
Here I wait for an input:
public Notification waitForNotification(){
try{
if(!(connected))return null;
DataInputStream inputStream = new DataInputStream(socket.getInputStream());
String input;
Log.e("Before Input", socket.getInetAddress()+"");
while((input = inputStream.readUTF()) != null){
Notification notification = new Notification(input);
return notification;
}
return null;
} catch (IOException e) {
e.printStackTrace();
Log.e("Lost Connection3", "ERROR");
connected = false;
return null;
}
}
And here I manage it:
#Override
protected void onHandleIntent(Intent intent) {
Log.e("HII", "HII");
username = getDataFromStorage.loginData(getApplicationContext())[0];
new Thread(new Runnable() {
#Override
public void run() {
ConnectionService connectionService = new ConnectionService(username);
while (true) {
if(!(connectionService.getConnectionState())){
try {
Thread.sleep(3000);
connectionService.reconnect();
continue;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Notification notification = connectionService.waitForNotification();
if(notification == null){
continue;
}
processStartNotification(notification);
}
}
}).start();
}
And here I start the connection:
public ConnectionService(String username){
this.username = username;
try{
socket = new Socket(BackgroundService.HOSTNAME, BackgroundService.PORT);
connected = true;
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
output.writeUTF(username);
output.flush();
}catch(UnknownHostException e){
connected = false;
}catch(IOException e){
connected = false;
}
}
Related
I am trying to connect an Android device to a java server. It works perfectly when I use the emulator but when I port it onto my phone there is no connection.
The aim of the code is to send a value from client to server, perform a calculation on it and return it back to the client to be displayed.
This is my server code:
public class ServerTest {
public static final int PORT_NUMBER = 8000;
protected Socket socket;
private ServerTest(Socket socket) {
this.socket = socket;
System.out.println("New client connected from " + socket.getInetAddress().getHostAddress());
connect();
}
public void connect() {
InputStream in = null;
OutputStream out = null;
try {
in = socket.getInputStream();
out = socket.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String request = br.readLine();
if (request.equals("end")) {
System.out.println("Message received: " + request + ". Ending connection.");
request = "End Connection";
out.write(request.getBytes());
in.close();
out.close();
socket.close();
System.exit(0);
} else {
System.out.println("Message received: " + request);
request = calculatePi(request);
System.out.println("Output: " + request);
out.write(request.getBytes());
}
} catch (IOException ex) {
System.out.println("Unable to get streams from client");
} finally {
try {
in.close();
out.close();
socket.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
System.out.println("Welcome. IP address is: " + getIP());
ServerSocket server = null;
try {
server = new ServerSocket(PORT_NUMBER);
while (true) {
new ServerTest(server.accept());
}
} catch (IOException ex) {
System.out.println("Unable to start server.");
} finally {
try {
if (server != null)
server.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
private static String getIP() {
String ip = "";
try {
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
NetworkInterface iface = interfaces.nextElement();
// filters out 127.0.0.1 and inactive interfaces
if (iface.isLoopback() || !iface.isUp())
continue;
Enumeration<InetAddress> addresses = iface.getInetAddresses();
while(addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
// *EDIT*
if (addr instanceof Inet6Address) continue;
ip = addr.getHostAddress();
}
}
} catch (SocketException e) {
throw new RuntimeException(e);
}
return ip;
}
and this is my client side code on device:
public class MainActivity extends AppCompatActivity {
TextView piResultTextView;
EditText addressEditText, messageEditText;
Button connectButton;
Handler handler = new Handler();
Results results;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
results = new Results();
addressEditText = findViewById(R.id.AddressEditText);
messageEditText = findViewById(R.id.MessageEditText);
connectButton = findViewById(R.id.ConnectButton);
connectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
connect();
}
});
piResultTextView = findViewById(R.id.PiResultTextView);
}
public void connect() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
String hostAddress = addressEditText.getText().toString();
int port = 8000;
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket(hostAddress, port);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
Toast.makeText(getApplicationContext(), "Unknown host: " + hostAddress, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Unable to get streams from server", Toast.LENGTH_SHORT).show();
}
String input = messageEditText.getText().toString();
try {
out.println(input);
results.pi = in.readLine();
handler.post(new Runnable() {
#Override
public void run() {
piResultTextView.setText(results.pi);
}
});
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Unable to read input stream from server", Toast.LENGTH_SHORT).show();
}
try {
out.close();
in.close();
echoSocket.close();
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Error closing streams", Toast.LENGTH_SHORT).show();
}
}
});
thread.start();
}
}
i'm begginer with java socket in android. i'm have some problem and need help for solving them.
I'm connect to server Socket with bottom code and every thing is fine. but when call disconnect method and try to connect again i faced with problem such socket is null or BufferedReader object always return null after disconnect and connect again. maybe my disconnect way is wrong. what is the best way for disconnect socket at some time like intrupt internet and connect again?
Here is my code for connecting and disconnecting socket.
public class HelperSocket {
public static Socket socket = null;
public static DataOutputStream writer = null;
public static BufferedReader reader = null;
public static DataInputStream inputStream = null;
public static final String SOCKET_ADDRESS = "aUrlForSocket";
public static final int SOCKET_PORT = 6000;
public static final int SOCKET_TIMEOUT = 30000;
public static Thread clientThread;
public static boolean isConnected = false;
public static boolean connect() {
Utils.Log("StartConnect");
if (!isConnected) {
clientThread = new Thread(new Runnable() {
#Override
public void run() {
try {
InetAddress address = InetAddress.getByName(HelperSocket.SOCKET_ADDRESS);
socket = new Socket(address.getHostAddress(), SOCKET_PORT);
isConnected = true;
socket.setSoTimeout(SOCKET_TIMEOUT);
writer = new DataOutputStream(socket.getOutputStream());
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
inputStream = new DataInputStream(socket.getInputStream());
while (HelperSocket.isConnected) {
Utils.Log("onWhile" + reader.hashCode());
try {
if (reader.readLine() != null) {
Utils.Log(reader.readLine() + "");
} else {
Utils.Log("getNullFromServer");
//data get null here :)
disconnect();
}
} catch (IOException e) {
Utils.Log("ProblemOnReadData" + e.getMessage());
e.printStackTrace();
}
}
} catch (IOException e) {
Utils.Log("SocketProblemAt connect:" + e.getMessage());
e.printStackTrace();
}
}
});
clientThread.start();
}
return true;
}
public static boolean disconnect() {
isConnected = false;
if (!clientThread.isInterrupted())
clientThread.interrupt();
if (socket != null) {
Utils.Log("SocketAndAllObjectCleared");
try {
socket.shutdownInput();
socket.shutdownOutput();
socket = null;
} catch (IOException e) {
e.printStackTrace();
}
/* stream = null;
reader = null;*/
}
return false;
}
}
I create a reciever in network connectivity change, and need to disconnect socket when device not connect to internet and connect again when internet connection established.
The receiver:
public class BroadcastChangeNet extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (Utils.isNetworkConnected()) {
HelperSocket.connect();
Utils.Log("NetWorkConnect");
} else {
HelperSocket.disconnect();
Utils.Log("NetWorkDisConnect");
}
}
}
Checking network situation:
public static boolean isNetworkConnected() {
ConnectivityManager conMgr =
(ConnectivityManager) ApplicationClass.context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo i = conMgr.getActiveNetworkInfo();
if (i == null)
return false;
if (!i.isConnected())
return false;
if (!i.isAvailable())
return false;
return true;
}
From my point of view you simply need to create saprate Jave class, below is my code that i tested successfully,
import android.content.Context;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
/**
* Created by Kintan Patel on 01-08-2016.
*/
public class SocketConnection {
private Socket socket = null;
private OutputStream outputStream;
private DataOutputStream dataOutputStream;
private SessionHelper helper;
public String EstablishConnection(String token) {
// token = your message that write on socket server
String response;
try {
//socket = new Socket("192.168.0.24", 2129); // Testing Server
socket = new Socket("Your IpAddress", PORT NO);
outputStream = socket.getOutputStream();
dataOutputStream = new DataOutputStream(outputStream);
dataOutputStream.writeUTF(token);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
response = br.readLine();
} catch (UnknownHostException e) {
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
return null;
} catch (SocketException e) {
e.printStackTrace();
response = "Sorry Fail to connect";
return null;
} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
response = "Sorry Fail to connect";
return null;
} catch (Exception e) {
e.printStackTrace();
response = "Server Break";
return null;
} finally {
if (socket != null) {
try {
socket.close();
outputStream.close();
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return response;
}
}
Now from your main class simply create the object of SocketConnection class and use EstablishConnection() method,
eg :
SocketConnection connection = new SocketConnection();
String token = "message that you want to write on server";
String response = connecation.EstablishConnection(token);
if you want to use AsynkTask than below is AsynkTask code :
private class ActivationTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
SocketConnection connection = new SocketConnection();
String token = "getActivation|" + params[0] + "|";
return connection.EstablishConnection(token);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.show();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
progressDialog.dismiss();
if (s != null) {
Log.e("RESULT" , s);
}
}
}
I am currently working on a project that requires an android app to connect to a java server that I have created. The problem is that the socket does not initialize. I have added the permissions to the AndroidManifest.xml file
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
My app code looks as follows:
Button Trigger:
View.OnClickListener btnDownloadListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
//Implement download code
try{
new ConnectionManager().execute("10.90.181.91" , "21002");
}catch(Throwable t){
}
}
};
ConnectionManager Background Function:
protected String doInBackground(String... args) {
try{
Log.i("Test", "background thread started");
int port = Integer.parseInt(args[1]);
InetAddress serverAddr = InetAddress.getByName(args[0]);
Socket connSock = new Socket(serverAddr, port);
Log.i("Test", "Created Socket");
}catch(Throwable t){
}
return "";
}
The log is outputting "background Thread Started", but never outputs "Created Socket"
The Server code is as follows:
Main method
try{
ServerSocket serverSocket = null;
boolean listeningSocket = true;
try {
serverSocket = new ServerSocket(21002);
} catch (IOException e) {
System.err.println("Could not listen on port: 21002");
}
int count = 0;
while(listeningSocket){
try{
Socket clientSocket = serverSocket.accept();
new ServerThread(clientSocket).start();
}catch(Throwable t){
}
}
System.out.println("You should not be here");
serverSocket.close();
}catch(Throwable t){
}
ServerThread
public class ServerThread extends Thread {
private Socket socket = null;
private String s;
private InputStream in;
private OutputStream out;
BufferedReader is;
BufferedWriter os;
public ServerThread(Socket s) {
socket = s;
System.out.println("Thread started: " + socket.getInetAddress());
try{
in = socket.getInputStream();
out = socket.getOutputStream();
out.flush();
is = new BufferedReader(new InputStreamReader(in));
os = new BufferedWriter(new OutputStreamWriter(out));
}catch(Throwable t){
t.printStackTrace();
}
}
public void run() {
System.out.println("Thread is running");
String dataType = "";
Boolean awaitingTransfer = false;
try {
while(true){
if(in.available() > 0 && !awaitingTransfer){
dataType = is.readLine();
System.out.println(dataType);
}
if(in.available() > 0 && awaitingTransfer){
try{
ArrayList<SpotCheck> tempList = new ArrayList<SpotCheck>();
while(in.available() > 0){
//tempList = (ArrayList<SpotCheck>) in.readObject();
}
ServerMain.manager.applyChanges(tempList);
awaitingTransfer = false;
}catch(Throwable t){
t.printStackTrace();
}
}
}
} catch (Exception e) {
e.printStackTrace();
try {
in.close();
out.close();
socket.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
Thanks for the help!
As an amateur coder, i just wanted to ask you that, can you just add a toast to the "catch()" blog of your doInBackground like that
catch(Exception e)
{
runOnUiThread(new Runnable(){
#Override
public void run(){
Toast.makeText(getApplicationContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
});
}
so it can show your problem more specifically and it will become easier to handle maybe. but again i am not sure if it works, i mean using toast in asynctask classes is a little bit more tricky.
I'm using an AsyncTask to establish a TCP Connection and sending/receiving data through it.
My current Code looks like this at the moment:
public class NetworkTask extends AsyncTask<Void, byte[], Boolean> {
Socket nsocket; //Network Socket
InputStream nis; //Network Input Stream
OutputStream nos; //Network Output Stream
boolean bSocketStarted = false;
byte[] buffer = new byte[4096];
#Override
protected void onPreExecute() {
Log.i(TAG, "onPreExecute");
}
#Override
protected Boolean doInBackground(Void... params) { //This runs on a different thread
boolean result = false;
try {
// Connect to address
Log.i(TAG, "doInBackground: Creating socket");
SocketAddress sockaddr = new InetSocketAddress("google.de", 80);
nsocket = new Socket();
nsocket.connect(sockaddr, 5000); //10 second connection timeout
if (nsocket.isConnected()) {
bSocketStarted = true;
nis = nsocket.getInputStream();
nos = nsocket.getOutputStream();
Log.i("AsyncTask", "doInBackground: Socket created, streams assigned");
Log.i("AsyncTask", "doInBackground: Waiting for inital data...");
int read = nis.read(buffer, 0, 4096); //This is blocking
while(bSocketStarted) {
if (read > 0){
byte[] tempdata = new byte[read];
System.arraycopy(buffer, 0, tempdata, 0, read);
publishProgress(tempdata);
Log.i(TAG, "doInBackground: Got some data");
}
}
}
} catch (IOException e) {
e.printStackTrace();
Log.i(TAG, "doInBackground: IOException");
result = true;
} catch (Exception e) {
e.printStackTrace();
Log.i(TAG, "doInBackground: Exception");
result = true;
} finally {
try {
nis.close();
nos.close();
nsocket.close();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Log.i(TAG, "doInBackground: Finished");
}
return result;
}
public boolean SendDataToNetwork(final byte[] cmd) { //You run this from the main thread.
// Wait until socket is open and ready to use
waitForSocketToConnect();
if (nsocket.isConnected()) {
Log.i(TAG, "SendDataToNetwork: Writing received message to socket");
new Thread(new Runnable() {
public void run() {
try {
nos.write(cmd);
}
catch (Exception e) {
e.printStackTrace();
Log.i(TAG, "SendDataToNetwork: Message send failed. Caught an exception");
}
}
}
).start();
return true;
}
else
Log.i(TAG, "SendDataToNetwork: Cannot send message. Socket is closed");
return false;
}
public boolean waitForSocketToConnect() {
// immediately return if socket is already open
if (bSocketStarted)
return true;
// Wait until socket is open and ready to use
int count = 0;
while (!bSocketStarted && count < 10000) {
try {
Thread.sleep(500);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
count += 500;
}
return bSocketStarted;
}
#Override
protected void onProgressUpdate(byte[]... values) {
try {
if (values.length > 0) {
Log.i(TAG, "onProgressUpdate: " + values[0].length + " bytes received.");
String str = new String(buffer, "UTF8");
Log.i(TAG,str);
tv.setText(str);
tv.setMovementMethod(new ScrollingMovementMethod());
}
} catch (Exception e) {
e.printStackTrace();
}
finally {}
}
#Override
protected void onCancelled() {
Log.i(TAG, "Cancelled.");
}
#Override
protected void onPostExecute(Boolean result) {
if (result) {
Log.i(TAG, "onPostExecute: Completed with an Error.");
} else {
Log.i(TAG, "onPostExecute: Completed.");
}
}
}
I can instantiate the Task and call SendDataToNetwork from my activity. However, all the text I pass to SendDataToNetwork, for example, 'GET / HTTP/1.1' is continously sent to the server.
How can I modify my Code to maintain the connection in doInBackground and do nothing until I call SendDataToNetwork and after sending bytes to the server just wait until new data is ready to be sent? Basically I want to run the AsyncTask until I explicitly cancel (= close the connection) it.
nsocket.connect(sockaddr, 5000); //10 second connection timeout
if (nsocket.isConnected()) {
The test is pointless. If the socket wasn't connected, connect() would have thrown an exception.
Your read loop is also fundamentally flawed, in that it doesn't keep reading. There are standard solutions as to how to read a stream, e.g.:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
Your waitForSocketToConnect() method doesn't really do anything useful either.
You need to rethink all this.
I write some client-server communication.
My server:
public class Server {
public synchronized static void sendPacket(Packet packet,
ObjectOutputStream server) {
try {
server.writeObject(packet);
server.flush();
} catch (IOException e) {
Log.d(TAG, "Error while sending a packet. Output stream is unaviable.");
}
}
public synchronized static Packet readPacket(ObjectInputStream sourceStream) {
Packet recivedPacket = null;
try {
recivedPacket = (Packet) sourceStream.readObject();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return recivedPacket;
}
/** Register user on the server */
private User registerUser(Socket socket) {
ClientUserLoginPacket newUserPacket = null;
ObjectInputStream ois = null;
ObjectOutputStream oos = null;
try {
Log.i(TAG, "Opening output stream...");
oos = new ObjectOutputStream(socket.getOutputStream());
if (oos != null)
Log.d(TAG, "Output stream opened");
Log.i(TAG, "Opening input stream...");
ois = new ObjectInputStream(socket.getInputStream());
if (ois != null)
Log.d(TAG, "Input stream opened");
} catch (StreamCorruptedException e1) {
Log.e(TAG, "Error while opening stream");
} catch (IOException e1) {
e1.printStackTrace();
}
// First packet MUST be register request
try {
Log.d(TAG, "Waiting for login packet from client...");
newUserPacket = (ClientUserLoginPacket) readPacket(ois);
Log.d(TAG, "Login packet from recived...");
} catch (Exception e) {
Log.e(TAG, "Can't recive login packet.");
}
User newUserInstance = null;
// TODO check if exists. or to map in the future
if (newUserPacket != null) {
newUserInstance = new User(socket, ois, oos, newUserPacket.nick);
users.add(newUserInstance);
Log.d(TAG, "User " + newUserPacket.nick + " registered.");
Server.sendPacket(new ServerLoginAcceptedPacket(), oos);
Log.d(TAG, "User accept confirmation sent.");
}
return newUserInstance;
}
#Override
public void run() {
Log.i(TAG, "Starting server...");
ServerSocket server;
try {
server = new ServerSocket(PORT);
Log.i(TAG, "Server started.");
server.setSoTimeout(0);
while (true) {
Log.i(TAG, "Waiting for players...");
final Socket socket = server.accept();
Log.i(TAG, "New player connected.");
new Thread(new Runnable() {
#Override
public void run() {
Log.i(TAG, "Try to register new player.");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
User user = registerUser(socket);
while (true) {
Log.i(TAG, "Waiting for packets from " + user.nick+"...");
Packet packet = readPacket(user.ois);
Log.i(TAG, "Packet from " + user.nick + " recived.");
if (packet instanceof ...) {
...
}
}
}
}).start();
}
} catch (IOException e) {
Log.i(TAG, "Port is busy.");
}
}
private class User {
public Socket connection;
public ObjectInputStream ois;
public ObjectOutputStream oos;
public String nick;
public boolean inGame;
public User(Socket socket, ObjectInputStream ois,
ObjectOutputStream oos, String nick) {
this.connection = socket;
this.ois = ois;
this.oos = oos;
this.nick = nick;
}
// ...
}
My client:
public class Client {
callbackHandler = new Thread(new Runnable() {
#Override
public void run() {
while (true) {
Log.e(TAG, "Waiting for incomeing packets...");
Packet packet = (Packet) Server.readPacket(serverInput);
Log.e(TAG, "Packet recived.");
if (packet instanceof ServerLoginAcceptedPacket) {
Log.e(TAG, "Recived packet is "
+ packet.getClass().toString());
Intent intent = new Intent(MyActivity.this,
MainMenuActivity.class);
MyActivity.this.startActivity(intent);
}
}
}
});
public void connectToServer() {
SocketAddress sockaddr = new InetSocketAddress(mEditTextIp.getText()
.toString(), Server.PORT);
server = new Socket();
try {
server.setSoTimeout(1000);
Log.d(TAG, "Connecting to server.");
server.connect(sockaddr, Server.PORT);
Log.d(TAG, "Connected to server.");
} catch (IOException e) {
Log.e(TAG, "Can't connect to server.");
server = null;
}
if (server != null)
try {
server.setSoTimeout(0);
Log.d(TAG, "Opening output stream...");
serverOutput = new ObjectOutputStream(server.getOutputStream());
if (serverOutput != null)
Log.d(TAG, "Output stream opened");
else
Log.e(TAG, "Error while opening output stream");
} catch (IOException e) {
Log.e(TAG, "Server socket probably closed");
}
}
public void requestLogin() {
new Thread(new Runnable() {
#Override
public void run() {
Log.e(TAG, "Sending login packet...");
Server.sendPacket(new ClientUserLoginPacket(mEditTextLogin
.getText().toString(), ""), serverOutput); // TODO send
// pass and
// email
Log.e(TAG, "Login packet send");
}
}).start();
}
public void authenticate(View v) {
if (server == null)
connectToServer();
if (server != null) {
requestLogin();
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
serverInput = new ObjectInputStream(server.getInputStream());
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (serverInput != null) {
Log.e(TAG, "Start reciving callbacks...");
callbackHandler.start();
} else {
Log.d(TAG, "Can't open input stream to server.");
}
}
}
public void runServer(View v) {
new Thread(new Server()).start();
Toast.makeText(this, "Server running...", 1000).show();
}
}
Where runServer() and authenticate() functions are triggered with button.
Problem is that after server recive ClientLoginPacket, all subsequent sentPacket functions hangs on oos.writeObject().
I think the order of reading/writing from/to streams may be wrong.
What should be correct order of opening streams and writing objects to them?
Do I have to write something to ObjectOutputStream before opening ObjectInputStream?
After few hours I found that keywords synchronized before my methods readPacket() and sendPacket() were problem. ;)