Can't user getOutputStream and getInputStream in a method [duplicate] - java

This question already has an answer here:
java.net.SocketException socket is closed
(1 answer)
Closed 5 years ago.
I have a application to connect 2 device using socket. In Client, i try send and receive data. When i send data from Client, the Server can receive data and reply a other message. But when i open InputStream to catch receive from server, it show notify (IOException: java.net.SocketException: Socket is closed).
Please help me. ##
CODE IN CLIENT:
Socket socket = null;
String mes = message;
try {
socket = new Socket(dstAddress, dstPort);
/*Example send data to server*/
ops = socket.getOutputStream();
ps = new PrintStream(ops);
ps.print(mes);
ps.close();
/*End of example*/
/*Receive data from server*/
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
/*End of Receive data from server*/
Log.e("Receive From Server:", response);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
AND THIS CODE OF SERVER
private class SocketServerThread extends Thread {
int count = 0;
#Override
public void run() {
try {
serverSocket = new ServerSocket(socketServerPORT);
while (true) {
Socket socket = serverSocket.accept();
count++;
/*example get input String*/
try {
isr = new InputStreamReader(socket.getInputStream());
br = new BufferedReader(isr);
request = br.readLine();
Log.e("Mess-H.a", request);
}catch (Exception e){
Log.e("Can't receive data:", e.getMessage() );
}
message += "#" + count + " from "
+ socket.getInetAddress() + ":"
+ socket.getPort() + request + "\n";
/*End of example*/
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
activity.msg.setText(message);
}
});
SocketServerReplyThread socketServerReplyThread = new SocketServerReplyThread(
socket, count);
socketServerReplyThread.run();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class SocketServerReplyThread extends Thread {
private Socket hostThreadSocket;
int cnt;
SocketServerReplyThread(Socket socket, int c) {
hostThreadSocket = socket;
cnt = c;
}
#Override
public void run() {
OutputStream outputStream;
String msgReply = "Hello from Server, you are #" + cnt;
try {
outputStream = hostThreadSocket.getOutputStream();
PrintStream printStream = new PrintStream(outputStream);
printStream.print(msgReply);
printStream.close();
message += "replayed: " + msgReply + "\n";
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
activity.msg.setText(message);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message += "Something wrong! " + e.toString() + "\n";
}
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
activity.msg.setText(message);
}
});
}
}

You closed the socket and then continued to use it.
ps.close();
Here. Remove.

Related

How to connect android device with bluetooth as server to 4 client devices and receive send data to server

I want to create two apps in android java, to connect through bluetooth and send and receive data. I already implement both apps. but the problem is when i want to connect more than one client to the server app and send data from all clients to the server. but server only can get data from first client. before i heard one server can connect to five client at the same time.
is it right?
private class Server extends Thread {
private BluetoothServerSocket serverSocket;
public Server() {
try {
serverSocket = bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(APP_NAME, uuid);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
BluetoothSocket bluetoothSocket = null;
while (bluetoothSocket == null) {
try {
bluetoothSocket = serverSocket.accept();
} catch (IOException e) {
e.printStackTrace();
}
if (bluetoothSocket != null) {
sendReceive = new SendReceive(bluetoothSocket);
sendReceive.start();
break;
}
}
}
}
private class SendReceive extends Thread {
private BluetoothSocket socket;
private InputStream inputStream;
private OutputStream outputStream;
public SendReceive(BluetoothSocket socket1) {
socket = socket1;
InputStream tempIn = null;
OutputStream tempOut = null;
try {
tempIn = socket.getInputStream();
tempOut = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
inputStream = tempIn;
outputStream = tempOut;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (true){
try {
bytes = inputStream.read(buffer);
Log.i(TAG, "server receive: " + new String(buffer, 0 , buffer.length).trim());
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] bytes){
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class Client extends Thread {
BluetoothDevice device;
BluetoothSocket socket;
public Client(BluetoothDevice device1) {
device = device1;
try {
socket = device.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
try {
socket.connect();
sendReceive = new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
Log.i("blt", "run Client " + e.getMessage());
}
}
}
private class SendReceive extends Thread {
private BluetoothSocket socket;
private InputStream inputStream;
private OutputStream outputStream;
public SendReceive(BluetoothSocket socket1) {
socket = socket1;
InputStream tempIn = null;
OutputStream tempOut = null;
try {
tempIn = socket.getInputStream();
tempOut = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
Log.i("blt", "SendReceive " + e.getMessage());
}
inputStream = tempIn;
outputStream = tempOut;
}
public void run() {
byte[] buffer = new byte[1024];
int bytes;
while (true) {
try {
bytes = inputStream.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void write(byte[] bytes) {
try {
outputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
what should i change in my code to be able to connect more than one client to the server and receive data from all clients?

Android Sockets not working in reality

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();
}
}

java.net.SocketException: socket closed

I am using socket to send image from server to multiple client but after sending one image to every client again when i try to send another image it say socket is close but i didn't even close the socket as well.
So i want to keep my server and client socket is alive until the activity is visible.
I am using service to run socket server after that i am getting all socket list to activity so below is my code for server side
if (mSocketArraylist != null) {
for (int i = 0; i < mSocketArraylist.size(); i++) {
Socket mSocket = mSocketArraylist.get(i);
try {
DataOutputStream out = new DataOutputStream(mSocket.getOutputStream());
ContentResolver cr = mContext.getContentResolver();
InputStream is = null;
try {
is = cr.openInputStream(Uri.parse(data.getData().toString()));
} catch (FileNotFoundException e) {
Log.d(TAG, e.toString());
}
copyFile(is, out);
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
Log.e("Socket value", "Socket is null");
}
For client also i am using service below its implementation
class clientThread implements Runnable {
#Override
public void run() {
if (wifiInfo != null) {
if (!wifiInfo.isGroupOwner) {
String host = wifiInfo.groupOwnerAddress.getHostAddress();
Socket clientSocket = new Socket();
OutputStream os = null;
try {
clientSocket.bind(null);
clientSocket.setKeepAlive(true);
clientSocket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
os = clientSocket.getOutputStream();
PrintWriter pw = new PrintWriter(os);
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ SocketClientService.this.getPackageName() + "/VR-" + System.currentTimeMillis()
+ ".jpg");
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
while (true) {
Log.d(TAG, "server: copying files " + f.toString());
InputStream inputstream = clientSocket.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
break;
}
signalActivity(f.getAbsolutePath());
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
} else {
Log.e(TAG, "This device is a group owner, therefore the IP address of the " +
"target device cannot be determined. File transfer cannot continue");
}
}
}
}
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[8192 * 8192];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
} catch (IOException e) {
Log.d(TAG, e.toString());
return false;
}
return true;
}
So any one can help me out in this , help would be appreciated.
signalActivity method implementation
public void signalActivity(String message) {
Bundle b = new Bundle();
b.putString("message", message);
clientResult.send(port, b);
}

How to send large file using socket in android

I have written this code to transfer file from server to client, but i am able to send only less than 1 Kb size of file. i want to send any size of file. It would be very helpful if you could modify my code:
File Sender(Server code)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
infoIp = (TextView) findViewById(R.id.infoip);
infoPort = (TextView) findViewById(R.id.infoport);
infoIp.setText(getIpAddress());
serverSocketThread = new ServerSocketThread();
serverSocketThread.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "SiteLocalAddress: "+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
public class ServerSocketThread extends Thread {
#Override
public void run() {
Socket socket = null;
try {
serverSocket = new ServerSocket(SocketServerPORT);
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
infoPort.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}});
while (true) {
socket = serverSocket.accept();
FileTxThread fileTxThread = new FileTxThread(socket);
fileTxThread.start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public class FileTxThread extends Thread {
Socket socket;
FileTxThread(Socket socket){
this.socket= socket;
}
#Override
public void run() {
File file = new File(Environment.getExternalStorageDirectory(),"test.mp3");
byte[] bytes = new byte[(int) file.length()];
BufferedInputStream bis;
try {
bis = new BufferedInputStream(new FileInputStream(file));
bis.read(bytes, 0, bytes.length);
OutputStream os = socket.getOutputStream();
os.write(bytes, 0, bytes.length);
os.flush();
// socket.close();
final String sentMsg = "File sent to: " + socket.getInetAddress();
System.out.println("socket getIntentAddress "+socket.getInetAddress());
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,sentMsg,Toast.LENGTH_LONG).show();
}});
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Ioexception"+e);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Ioexception"+e);
}
File Receiver(Client Code)
buttonConnect.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
ClientRxThread clientRxThread =
new ClientRxThread(editTextAddress.getText().toString(),SocketServerPORT);
clientRxThread.start();
}});
}
private class ClientRxThread extends Thread {
String dstAddress;
int dstPort;
ClientRxThread(String address, int port) {
dstAddress = address;
dstPort = port;
}
#Override
public void run() {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
File file = new File(Environment.getExternalStorageDirectory(),"test.mp3");
byte[] bytes = new byte[1024];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
int bytesRead = is.read(bytes, 0, bytes.length);
bos.write(bytes, 0, bytesRead);
bos.close();
// socket.close();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,"Finished",Toast.LENGTH_LONG).show();
}});
} catch (IOException e) {
e.printStackTrace();
final String eMsg = "Something wrong: " + e.getMessage();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this,eMsg,Toast.LENGTH_LONG).show();
System.out.println("run"+eMsg);
}});
} finally {
if(socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Please help Sir! Thanks in advance!
You need to put the receiving of the bytes in a loop that only completes when all the data has been received. For example:-
byte[] bytes = new byte[1024];
InputStream is = socket.getInputStream();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
while (true) {
int bytesRead = is.read(bytes);
if (bytesRead < 0) break;
bos.write(bytes, 0, bytesRead);
// Now it loops around to read some more.
}
bos.close();
I could have sworn your original questions was about receiving, not sending (and other answers seem to suggest the same).
Regardless, to send large files, you can either read your entire file into a buffer large enough to hold it (assuming the file is of a reasonable size), or use a loop to read it in chunks of a manageable size and then process (send) the chunks.
In answer to your original question, you are only reading 1024 because that is all you are attempting to read. You have allocated your buffer at 1024 and only reading once.
byte[] bytes = new byte[1024];
...
int bytesRead = is.read(bytes, 0, bytes.length);
bos.write(bytes, 0, bytesRead);
bos.close();
try
byte[] bytes = new bytes[1024];
...
int bytesRead = is.read(bytes, 0, bytes.length);
while(bytesRead > 0) {
bos.write(bytes, 0, bytesRead);
bytesRead = is.read(bytes, 0, bytes.length);
}
...
and wrap your code at an appropriate spot with a try/catch block in case of an exception.

ObjectOutputStream method writeObject hangs on android

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. ;)

Categories