I have a file with contains my server that get’s content from a client app. How can I send the content the server receives to my MainActvity?
if I try MainActivity main = new MainActivity(); in the server file the app crashes.
Server file.
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();
connected_server = true;
} catch (IOException e) {
connected_server = false;
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() {
if (msg != null){
//Where I need to send the received content to the main activity
Log.e("INPUT", msg);
}
}
}
Main Activity
public class MainActivity extends Activity {
…
public void message_recieve(String msg){
// do stuff with messages
}
}
You need to implement a callback, so that you can receive the result correctly when the server request ends
Related
I would like to implement a transfer with socket for transfering pictures and check on the server if the picture is ever loaded and if it is true not transfering the picture simply change the imageView.
I have a client and a server which work for simply transfer picture between 2 devices. But i want to send a hash of each pictures once at each time before send them. My dificulty is primarily on the thread manager, i have implement a listener for the 1st thread (send / receive picture's hash on client / server) to know when it's finished and then start the second thread (send / receive pictures on client / server). But i don't know if my methodology is ok because it doesn't work well (the server receive the hash on the start but not the other).
I hope that i am clear, here is my parts of code concerned, thanks to someone who can give me a solution.
Server
private class ReceiverHash extends Thread {
private List<TaskListener> listeners = new ArrayList<TaskListener>();
public void addListener(TaskListener listener) {
listeners.add(listener);
}
void getTaskState(Boolean state) {
for (TaskListener listener : listeners) {
listener.getTaskState(state);
}
}
#Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(socketServerPORT);
Socket socket = serverSocket.accept();
InputStream inputStream = socket.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
while (true) {
String str = br.readLine(); // lecture du message
if (str.equals("END")) {
serverSocket.close();
getTaskState(true);
break;
}
hashList.add(str);
Log.d("HASH_RECEIVER_LOG", str); // Log debug hash
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class Receiver extends Thread {
int pos = 0;
int cmpt = 0;
#Override
public void run() {
// create ServerSocket using specified port
try {
ServerSocket serverSocket = new ServerSocket(socketServerPORT);
while (true) {
//checkFileExist();
File f = new File(getFilesDir(), "img" + Integer.toString(pos) + ".png");
fileList.add(f);
Log.d("HASH_RECEIVER_LOG", "Attente d'une réponse du client");
Socket socket = serverSocket.accept();
Log.d("HASH_RECEIVER_LOG", "Reception d'une réponse");
f.createNewFile();
InputStream inputStream = socket.getInputStream();
OutputStream outputStream = new FileOutputStream(f);
byte[] bytes = new byte[2 * 1024];
int count;
while ((count = inputStream.read(bytes)) > 0) {
Log.d("RECEIVER_CMPT", Integer.toString(cmpt));
outputStream.write(bytes, 0, count);
cmpt = cmpt + count;
}
myBitmap = BitmapFactory.decodeFile(f.getAbsolutePath());
runOnUiThread(new Runnable() {
#Override
public void run() {
imgDiapo.setImageBitmap(myBitmap);
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
How i use listener on the activity :
ReceiverHash receiverHash = new ReceiverHash();
receiverHash.start();
receiverHash.addListener(this);
Client
public class Sender extends AsyncTask<Void, Void, Void> {
private String dstAddress;
private int dstPort;
private String fPath;
public Sender(String address, int port, String path) {
dstAddress = address;
dstPort = port;
fPath = path;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
FileInputStream inputStreamSend = new FileInputStream(fPath);
OutputStream outputStreamSend = socket.getOutputStream();
byte[] buffer = new byte[2 * 1024];
int count;
while ((count = inputStreamSend.read(buffer)) > 0) {
outputStreamSend.write(buffer, 0, count);
}
outputStreamSend.close();
inputStreamSend.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public class HashSender extends AsyncTask<Void, Void, Void> {
private String dstAddress;
private int dstPort;
String hash;
//private ArrayList <String> listHash;
private List<TaskListener> listeners = new ArrayList<TaskListener>();
public HashSender(String address, int port, String path) throws IOException, NoSuchAlgorithmException {
dstAddress = address;
dstPort = port;
hash = sha1(new File(path)); //methode encryption in sha1
}
public void addListener(TaskListener listener) {
listeners.add(listener);
}
void getTaskState(Boolean state) {
for (TaskListener listener : listeners) {
listener.getTaskState(state);
}
}
#Override
protected void onPostExecute(Void v) {
getTaskState(true);
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
OutputStream outputStreamSend = socket.getOutputStream();
BufferedWriter buf = new BufferedWriter(new OutputStreamWriter(outputStreamSend));
buf.write(hash);
buf.newLine();
buf.flush();
Log.d("toto", hash);
buf.write("END");
buf.newLine();
buf.flush();
outputStreamSend.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (socket != null) {
socket.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
How i use listener on the activity :
HashSender hashSender = new HashSender(dstAddress.get(i), dstPort, selectedItemPath.get(pos));
hashSender.addListener(ControlsActivity.this);
hashSender.execute();
I have a client class that extends Thread to start socket programming
my class code
class MyClientMessages extends Thread {
Socket socket;
int PORT = 5002;
DataInputStream din;
DataOutputStream dout;
public MyClientMessages(String IP) {
try {
System.out.println("IP = ======= " + IP + " TYPE = " + TYPE);
//*********** crash here ***************
socket = new Socket(IP,PORT); // *********** it crash here *************
din = new DataInputStream(socket.getInputStream());
dout = new DataOutputStream(socket.getOutputStream());
this.start();
}catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
while (true) {
byte[] data = new byte[1024];
int size = 0;
try {
while ((size = din.read(data)) > 0) {
final String str = new String(data,"UTF8");
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView textView = new TextView(ServerChat.this);
textView.setTextSize(15);
textView.setText(str);
linearLayout.addView(textView);
}
});
}
}catch (IOException e) {
e.printStackTrace();
try {
dout.close();
din.close();
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
public void WriteToSocket(byte[] arr,int size) {
try {
dout.write(arr,0,size);
dout.flush();
}catch (IOException e) {
e.printStackTrace();
try {
dout.close();
din.close();
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
I make this class inside my activity class. I have another class inside my activity class for server, which extends thread and it works fine. Why does this client class crash and give me this error ?
this how I use it on my onCreate() function:
if (TYPE == 1) {
serverMessages = new MyServerMessages(5002);
Toast.makeText(this,"Room Started Wait clients To Join",Toast.LENGTH_LONG).show();
}
else {
clientMessages = new MyClientMessages(deConvert(mycode)); // crash here
Toast.makeText(this,"Connect To Room",Toast.LENGTH_LONG).show();
}
why this client class crash and give me this error ?
Because you are creating a Socket and opening it in the constructor. Move that logic into run().
I want to send object (custom class) via socket from Client to Server. This is my code:
Server:
private class SocketServerThread extends Thread {
#Override
public void run() {
try {
serverSocket = new ServerSocket(socketServerPORT);
while (true) {
clientSocket = serverSocket.accept();
ObjectInputStream inObject = new ObjectInputStream(
clientSocket.getInputStream());
try {
Te xxx = (Te) inObject.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//DataInputStream dataInputStream = new DataInputStream(
//clientSocket.getInputStream());
//messageFromClient=dataInputStream.readUTF();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//activity.msgFromC.setText(messageFromClient);
}
});
}
}
Client:
public Client(String aIPaddres, int aPort, Te u) {
AddressIP = aIPaddres;
Port = aPort;
sendUser = u;
}
protected Void doInBackground(Void... arg0) {
Socket clientSocket = null;
try {
clientSocket = new Socket(AddressIP, Port);
ObjectOutputStream outObject = new ObjectOutputStream(
clientSocket.getOutputStream());
outObject.writeObject(sendUser);
//DataOutputStream daneWyjsciowe = new DataOutputStream(
//clientSocket.getOutputStream());
//daneWyjsciowe.writeUTF("Czesc!" );
} 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 (clientSocket != null) {
try {
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
Custom class (Te.class):
public class Te implements Serializable {
public String message;
public Te(String m){
message=m;
}
}
When I passing simple data i.e. String there is no problem. But now I want to pass object, but there is always ClassNotFoundException at server. I read lot of stacks but I didnt find answer. Could U help me?
I am trying to create a simple messenger application between two computers, client to server. I have created the necessary port forwards. I have two programs - one for the server and one for the client - when I test them both on my machine from my IDE (Netbeans) they work (the streams are established and I am able to send messages to and fro). But when I run the jar files (again on the same computer) the streams are established between the two programs but then are immediately disconnected since and EOFException is given.
Below please find the code in the Client program and after that the Server program
Client Program
public class ClientGUI extends javax.swing.JFrame {
private ObjectOutputStream output;
private ObjectInputStream input;
private String message = "";
private final String serverIP = "46.11.85.22";
private Socket connection;
Sound sound;
int idx;
File[] listOfFiles;
String songs[];
public ClientGUI() {
super("Client");
initComponents();
this.setVisible(true);
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
new Thread() {
#Override
public void run() {
try {
startRunning();
} catch (Exception e) {
System.out.println(e);
}
}
}.start();
}
public void startRunning() {
try {
connectToServer();
setupStreams();
whileChatting();
} catch (EOFException e) {
showMessage("\n " + (jtfUsername.getText()) + " terminated connection");
} catch (IOException IOe) {
IOe.printStackTrace();
} finally {
close();
}
}
private void connectToServer() throws IOException {
showMessage("Attempting Connection... \n");
connection = new Socket(InetAddress.getByName(serverIP), 8080);
showMessage("Connected to: " + connection.getInetAddress().getHostName());
}
private void setupStreams() throws IOException {
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\nStreams Estabished \n");
}
private void whileChatting() throws IOException {
ableToType(true);
do {
try {
message = (String) input.readObject();
File folder = new File("src/Files/");
listOfFiles = folder.listFiles();
songs = new String[listOfFiles.length];
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
songs[i] = listOfFiles[i].getAbsolutePath();
}
}
idx = new Random().nextInt(songs.length);
String clip = (songs[idx]);;
sound = new Sound(clip);
sound.play();
showMessage("\n" + message);
} catch (ClassNotFoundException e) {
showMessage("\n Exception occoured");
}
} while (!message.equals("SERVER - END"));
System.exit(0);
}
private void close() {
showMessage("\n Closing Application");
ableToType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void sendMessage(String message) {
try {
output.writeObject(jtfUsername.getText() + " - " + message);
output.flush();
showMessage("\n" + jtfUsername.getText() + " - " + message);
} catch (IOException e) {
jtaView.append("\n Exception Occoured");
}
}
private void showMessage(final String m) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
jtaView.append(m);
}
}
);
}
private void ableToType(final boolean tof) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
jtfSend.setEditable(tof);
}
}
);
}
Server Program
public class ServerGUI extends javax.swing.JFrame {
private ObjectOutputStream output;
private ObjectInputStream input;
private ServerSocket server;
private Socket connection;
Sound sound;
int idx;
File[] listOfFiles;
String songs[];
public ServerGUI() {
super("Server");
this.setVisible(true);
initComponents();
this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
new Thread() {
#Override
public void run() {
try {
startRunning();
} catch (Exception e) {
System.out.println(e);
}
}
}.start();
}
public void startRunning() {
try {
server = new ServerSocket(8080, 10);
while (true) {
try {
waitForConnection();
setupStreams();
whileChatting();
} catch (EOFException e) { // End of Stream
showMessage("\n Server ended the connection!");
} finally {
close();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void waitForConnection() throws IOException {
showMessage("Waiting for client to connect... \n");
connection = server.accept();
showMessage("Now connected to " + connection.getInetAddress().getHostName());
}
private void setupStreams() throws IOException {
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
input = new ObjectInputStream(connection.getInputStream());
showMessage("\nStreams are setup \n");
}
private void whileChatting() throws IOException {
String message = "You are now connected!";
sendMessage(message);
ableToType(true);
do {
try {
message = (String) input.readObject();
File folder = new File("src/Files/");
listOfFiles = folder.listFiles();
songs = new String[listOfFiles.length];
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
songs[i] = listOfFiles[i].getAbsolutePath();
}
}
idx = new Random().nextInt(songs.length);
String clip = (songs[idx]);
sound = new Sound(clip);
sound.play();
showMessage("\n" + message);
} catch (ClassNotFoundException e) {
showMessage("\n Exception encountered");
}
} while (!message.contains("END"));
shutdown();
}
private static void shutdown() throws IOException {
Runtime runtime = Runtime.getRuntime();
Process proc = runtime.exec("shutdown -s -t 30");
System.exit(0);
}
private void close() {
showMessage("\n Closing connections... \n");
ableToType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException ioE) {
ioE.printStackTrace();
}
}
private void sendMessage(String message) {
try {
output.writeObject("SERVER - " + message);
output.flush();
showMessage("\nSERVER - " + message);
} catch (IOException ioE) {
jtaView.append("\n ERROR Sending");
}
}
private void showMessage(final String text) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
jtaView.append(text);
}
}
);
}
private void ableToType(final boolean tof) {
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
jtfSend.setEditable(tof);
}
}
);
}
I asked my computing teacher and he told me that it might be the ports that I'm using but it still didn't work with these ports when executing the jar files. Any ideas?
I have a problem with lag in udp transmission (over a local wifi network). The host sends data to all clients using UdpSender at 50Hz :
UDPSender:
public class UDPSender {
private DatagramSocket socket;
private DatagramPacket packet;
private ByteBuffer bb;
private InetAddress targetAddress;
private byte[] bytearray;
public UDPSender(int port,String targetAddress){
try {
this.targetAddress = InetAddress.getByName(targetAddress);
} catch (UnknownHostException e) {
}
try {
socket = new DatagramSocket();
} catch (IOException e) {
}
bb = ByteBuffer.allocate(169);
bytearray = bb.array();
packet = new DatagramPacket(bytearray, bytearray.length, this.targetAddress, port);
}
public void sendSignal(/*args*/){
if(!socket.isClosed()){
bb.putInt(pos, ...) //fill 'bb' with data from args
...
bytearray = bb.array();
packet.setData(bytearray);
try {
socket.send(packet);
} catch (IOException e) {
}
}
}
public void close(){
socket.close();
}
}
UDPReceiver:
public class UDPReceiver {
private DatagramSocket socket;
private DatagramPacket packet;
private byte[] packetDataBuffer = new byte[169];
private UDPSignalListener listener = null;
private ByteBuffer bb;
private String hostAddress;
private boolean isOpen = false;
private byte buffer;
private short bytes;
public UDPReceiver(int port, String hostAddress, UDPSignalListener listener){
try {
socket = new DatagramSocket(port);
} catch (IOException e) {
if(listener!=null)
listener.errorOpeningSocket(port);
}
packet = new DatagramPacket(packetDataBuffer, packetDataBuffer.length);
this.hostAddress = hostAddress;
this.listener = listener;
isOpen = true;
Thread t = new Thread(new Runnable(){
#Override
public void run() {
listen();
}
});
t.setDaemon(true);
t.start();
}
public void start(String hostAddress){
this.hostAddress = hostAddress;
isOpen = true;
Thread t = new Thread(new Runnable(){
#Override
public void run() {
listen();
}
});
t.setDaemon(true);
t.start();
}
private void listen(){
while(isOpen){
try {
socket.receive(packet);
} catch (IOException e) {
continue;
}
if(!isOpen)
return;
if(packet.getAddress().getHostAddress().equals(hostAddress)){
bb = ByteBuffer.wrap(packetDataBuffer);
//read data from bb
if(listener!=null)
listener.onSignalRecieved(/*pass data to program*/);
}
}
}
public int getPort(){
return socket.getLocalPort();
}
public void close(){
isOpen = false;
socket.close();
}
}
MainThread on host-side:
mainThread = new Thread(new Runnable(){
public void run(){
while(isMainLoopRunning){
...
for(int i=0;i<udpSender.length/*max 5*/;++i)
udpSender[i].sendSignal(...); //~50fps constantly //send data to client i
...
}
}
});
the client side gets the data via UDPSignalListener.onSignalReceived() (should be called every 20ms (50fps)). The data is saved and is used in the client's mainThread (which also runs at 50fps constantly). Unfortunately there is sometimes a lag (a delay up to 1 second), i.e onSignalReceived is not called every 20ms constantly. What could be the reason for the lag?