I'm trying to make a simple chatting app, using socket communication.
My goal is to send and receive text and images(from smartphone gallery) successfully.
Text part successful, but I'm having trouble with images.
I wrote a code using dataInput/OutputStream, and below is the code, which is establishing socket connection for image transfer, using bytearray(The app use different port for text and image).
class image_connection_thread extends Thread{
public boolean flag=true;
public void run(){
try{
socket2 = new Socket(Ip,port_img);
//Imgage Streams
img_output= new DataOutputStream(socket2.getOutputStream());
img_input= new DataInputStream(socket2.getInputStream());
while(flag)
{
///////////////////
img_input.readFully(byte_input);
**////// This line makes problem(App dies). But no exception message occurs. ////**
if(byte_input==null)
break;
image_received=BitmapFactory.decodeByteArray(byte_input, 0, byte_input.length);
Message Msg = new Message();
Msg.obj=image_received;
handler_img.sendMessage(Msg);
}
socket2.close();
}catch(Exception e)
{
tv_Text.append(e.getMessage()+"connection failed3\n");
}
}
}
While loop is to wait for input bytearray from server. Handler displays decoded bytearray on display.
--> img_input.readFully(byte_input); I think this line makes problem. I checked that handler works well, and with empty while block, App didn't die.
What would be the problem?
Server side code is shown below.(message threads are omitted)
public class server
{
public static void main(String[] args) {
Thread thread1=new port1_thread();
Thread thread2=new port2_thread();
thread1.start();
thread2.start();
}
}
class port2_thread extends Thread
{
ServerSocket serversocket = null;
public void run()
{
try
{
serversocket = new ServerSocket(9003);
while(true)
{
Socket socket = serversocket.accept();
Thread thread= new image_thread(socket);
thread.start();
}
}catch(Exception e){System.out.println("1-2"+e.getMessage());}
}
}
class image_thread extends Thread
{
static ArrayList<DataOutputStream> list2 = new ArrayList<DataOutputStream>();
Socket socket;
DataOutputStream output2 = null;
image_thread(Socket socket)//constructor
{
this.socket=socket;
try //data output stream
{
output2 = new DataOutputStream(socket.getOutputStream());
list2.add(output2);
}
catch (Exception e)
{
System.out.println("22"+e.getMessage());
}
}
public void run()
{
try
{
//output2= new DataOutputStream(socket.getOutputStream());
DataInputStream input2=new DataInputStream(socket.getInputStream());
while(true)
{
for (DataOutputStream output2 : list2)
{
byte[] b = new byte[1024];
input2.readFully(b);
output2.write(b);
output2.flush();
}
}
}catch(Exception e){System.out.println("33"+e.getMessage());}
finally
{
list2.remove(output2);
try
{
socket.close();
}catch(Exception ignored){}
}
}
}
Related
I am trying to pass keyboard values to an android client to push it to a server.
I am using threads, but don't want to run a new thread or call socketconnect each time. Instead, I want to run a single thread, open socket connection and then use the same thread and already opened socket to push some values to server from keyboard.
A runnable example with handler will work in my case but I don't know how to code it. ASYNCTASKS wont help as it would open connection again and again.
My Connection class is
class conThread implements Runnable {
public Handler dataHandler = new Handler() ;
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);//}
} catch (IOException e) {
e.printStackTrace();
}
}
}
**and my button has got the below code to send values to the thread for passing on to the server **
public void dataSend(View view) {
conThread con = new conThread();
new Thread(con).start();
con.dataHandler.post(new Runnable() {
public void run() {
try {
PrintWriter out = new PrintWriter(socket.getOutputStream());
Log.d("Client", "S: data");
out.print("3333");
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
I get connected to the server but get a crash after that.
I attempting to build a remote controller for my laptop using my phone.
I written a server application that running on my laptop, the remote app used as a client to the server application.
I want to implement a mouse pad, the problem is when I am moving my finger over the "touch pad" too fast, I am receiving read time out on server side after few iterations.
Server code
final ExecutorService clientProcessingPool = Executors.newFixedThreadPool(20);
Runnable serverTask = new Runnable()
{
#Override
public void run()
{
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(DEFAULT_PORT);
serverSocket.setReuseAddress(true);
_working = true;
while (_working)
{
Socket clientSocket = serverSocket.accept();
clientSocket.setSoTimeout(10000);
clientProcessingPool.submit(new ClientTask(clientSocket));
}
}
catch (IOException e)
{
System.err.println("Unable to process client request");
e.printStackTrace();
}
finally
{
try
{
if (serverSocket != null)
{
serverSocket.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
};
Thread serverThread = new Thread(serverTask);
serverThread.start();
private class ClientTask implements Runnable
{
private final Socket clientSocket;
private ClientTask(Socket clientSocket)
{
this.clientSocket = clientSocket;
}
#Override
public void run()
{
System.out.println("Got a client !");
try
{
System.out.println("Connected!");
DataOutputStream dOut = new DataOutputStream(clientSocket.getOutputStream());
DataInputStream dIn = new DataInputStream(clientSocket.getInputStream());
String request = dIn.readUTF();
parseRequest(request);
System.out.println("request=" + request);
dOut.writeUTF("Got the command");
dOut.flush(); // Send off the data
dIn.close();
dOut.close();
clientSocket.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
I thought maybe I will send the requests only if the distance from the starting position to end position is bigger than STEPS(a constant) and only then send the request. But I think the mouse won`t move fluidly.
Thanks.
RXAndroid and RXJava are perfect for asynchronously handling these request and will allow you to add a debounce to the frequent requests. Check out Reactive.io
I am developing an android application in which I have to create a multiple clients connection with one server. At the server side I am creating a new thread for every client and it is working fine, but in the new created thread where I am listening for a messages from socket and updating a list view created in a fragment, it is not getting updated. Please help me to solve this issue.
public class ClientSocketHandler extends Thread {
private static final String TAG = "ClientSocketHandler";
//private Handler handler;
// private ChatManager chat;
private InetAddress mAddress;
InputStream dataInputStream=null;
OutputStream dataOutputStream=null;
static String msgToSend="";
int i;
char c;
String newMsg="";
Boolean flag=true;
WiFiChatFragment frg;
Handler handler;
public ClientSocketHandler(InetAddress groupOwnerAddress) {
this.mAddress = groupOwnerAddress;
//this.handler=handl;
}
#Override
public void run() {
Socket socket = new Socket();
try {
socket.bind(null);
socket.connect(new InetSocketAddress(mAddress.getHostAddress(),
WiFiServiceDiscoveryActivity.SERVER_PORT), 5000);
Log.d(TAG, "Launching the I/O handler");
dataInputStream = socket.getInputStream();
dataOutputStream = socket.getOutputStream();
while (true) {
while(flag){
if((i=dataInputStream.read())!=1){
frg.pushMessage(newMsg);
newMsg="";
flag=false;
}
else{
c=(char)i;
newMsg+=c;}
}
if(!msgToSend.equals("")){
dataOutputStream.write(msgToSend.getBytes());
dataOutputStream.flush();
msgToSend = "";
}
}
} catch (IOException e) {
e.printStackTrace();
try {
socket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return;
}
}
public static void sendMsg(String msg){
msgToSend = msg;
}
}
I think this can happen of any of the following this is not handled.
1. Set the list adapted
2. Check that data is received on client and added to the data source.
3. Call the notifyDataSetChanged() after adding the data to data source for ListView.
This is my first post at the stackoverflow...
I am dealing with android app few weeks ago so my Knoledge is limited.
I want to send and receive UDP pakets enery 5 secs.I found example code BUT it use a button for that.
That is the code:
class Client implements Runnable
{
public Client()
{
}
#Override
public void run() {
try
{
String outMessage = txtOutMessage.getText().toString();
String outIp = txtOutIp.getText().toString();
int outPort = Integer.parseInt(txtOutPort.getText().toString());
InetAddress serverAddr = InetAddress.getByName(outIp);
DatagramSocket socket = new DatagramSocket();
byte[] buf = outMessage.getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length, serverAddr, outPort);
socket.send(packet);
byte[] receiveData = new byte[1024];
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
socket.receive(receivePacket);
final String recvMsg = new String(receivePacket.getData()).trim();
runOnUiThread(new Runnable()
{
#Override
public void run() {
txtInMessage.setText(recvMsg);
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
Please advice
Thanks in advanced
Nikos
Why not try using a thread? Something like this would work:
//create a thread
Thread t = new Thread()
{
#Override
public void run()
{
while (true)
{
try
{
//do your stuff
Thread.sleep(5000);
//thread to sleep for 5 seconds (5000 milliseconds)
} catch (InterruptedException ie)
{
ie.printStackTrace(); //catch the exception for thread.sleep
}
}
}
};
t.start(); //start the thread
I have something very similar but mine checks for incoming data ever 100 milliseconds and checks for outgoing data every 250 milliseconds, I have one thread for each of those, I then have a separate thread which runs every 20 seconds to check the socket to make sure its alive and to do some socket validation, and to create a new socket if its failed.
Hey community I have the following ServerSocket which should listen to port 53000 and log any received data. However, I cannot seem to get past the server.accept() blocking call.
public void run() {
SocketServer server = new ServerSocket(53000);
//---buffer store for the stream---
byte[] buffer = new byte[1024];
//---bytes returned from read()---
int bytes;
//---keep listening to the InputStream until an
// exception occurs---
while (true) {
try {
socket = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str = in.readLine();
Log.i("received response from server", str);
in.close();
socket.close();
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} catch (Exception e){
server.close();
Log.e(TAG, e.getMessage());
}
}
}
I have also given the application the INTERNET permission in the Manifest file.
()
To add to the mystery, I have also verified client responses get sent to that port.
Is there something in particular I need to do to make this work?
Thanks.
Your code is very messy and won't even compile. I made some adjustments so that i could test your code, and it's working fine. Here is the test application I used:
package com.test.stackoverflow
import java.io.BufferedReader;
public class ServerSocketTestActivity extends Activity {
/** Called when the activity is first created. */
private static String TAG = "ServerSocketTest";
private ServerSocket server;
Runnable conn = new Runnable() {
public void run() {
try {
server = new ServerSocket(53000);
while (true) {
Socket socket = server.accept();
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String str = in.readLine();
Log.i("received response from server", str);
in.close();
socket.close();
}
} catch (IOException e) {
Log.e(TAG, e.getMessage());
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Thread(conn).start();
}
#Override
protected void onPause() {
super.onPause();
if (server != null) {
try {
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Using this code and netcat running via adb shell I was able to connect and communicate with the application.
When working with The Client Declare these methods
To access Streams
// gets the input stream // ObjectInputStream input;
// gets the output stream // ObjectOutputStream output;
// ServerSocket server;
// Socket connection;
maybe you have a another class to access the socket;
server = new ServerSocket(5001, 100);
// step 1 create socket connection
server = new ServerSocket(5001, 100);
while(the condition is true)
// step 2 wait for connection
// step 3 get streams
// step 4 : process the connection
// step 5 : close connection