I am doing java server on my pc and having my android device connect to it. I can connect it but it disconnects as soon as it connects. I am sure there is something I need to do on the android side but I am little lost on it. I have the internet permission so that is fine.
Also ignore the commented code I was sending image from my android to pc. Also ignore the savebitmap and take screenshot I don't think its affecting the connection if its not being called.
Java Server:
import javax.imageio.ImageIO;
import javax.imageio.ImageReadParam;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.*; //access JFrame
import javax.swing.text.html.HTMLDocument.Iterator;
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
public class tcpmain {
BufferedReader in;
static final int PORT = 9000;
public static void main(String[] args) {
// TODO Auto-generated method stub
//lines to make the gui frame
JFrame mainframe = new JFrame();
mainframe.setTitle("TCP Listener");
mainframe.setSize(600,800);
mainframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainframe.setVisible(true);
ServerSocket serverSocket = null;
Socket socket = null;
try{
serverSocket = new ServerSocket(PORT);
//Receive code
/*int filesize=450660;
int bytesRead;
int current=0;
//receive file
byte [] mybytearray = new byte [filesize];
InputStream is = srsvsock.getInputStream();
FileOutputStream fos = new FileOutputStream("C:\\Users\\Andy\\Desktop\\testimage.jpg");
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;*/
/*do{
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0, current);
bos.flush();*/
}
catch(Exception e){
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
JOptionPane.showMessageDialog(null, "Client connected", "ALERT", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
System.out.println("I/O error: " + e);
}
// new threa for a client
new EchoThread(socket).start();
if ( socket != null && !socket.isClosed() ){
try {
socket.close();
JOptionPane.showMessageDialog(null, "Client Disconnected", "ALERT", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
client handler for java server
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
public class EchoThread extends Thread {
protected Socket socket;
public EchoThread(Socket clientSocket){
this.socket = clientSocket;
}
public void run(){
InputStream inp = null;
BufferedReader brinp = null;
DataOutputStream out = null;
try{
inp = socket.getInputStream();
brinp = new BufferedReader(new InputStreamReader(inp));
out = new DataOutputStream(socket.getOutputStream());
}catch(Exception e){
return;
}
String line;
while(true){
try{
line = brinp.readLine();
if ((line == null) || line.equalsIgnoreCase("QUIT")){
socket.close();
return;
}else{
out.writeBytes(line+ "\n\r");
out.flush();
}
}catch(Exception e){
e.printStackTrace();
return;
}
}
}
}
Here is android client:
package com.example.tcpsocket;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Socket socket;
private static final int SERVERPORT = 9000;
private static final String SERVER_IP = "192.168.1.113";
Bitmap bitmap;
File imagePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnconnect = (Button)findViewById(R.id.button1);
btnconnect.setOnClickListener(connect);
}
private OnClickListener connect = new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
//Bitmap bitmap = takeScreenshot();
// saveBitmap(bitmap);
new Thread(new clienthread()).start();
}
};
public Bitmap takeScreenshot() {
View rootView = findViewById(android.R.id.content).getRootView();
rootView.setDrawingCacheEnabled(true);
return rootView.getDrawingCache();
}
public void saveBitmap(Bitmap bitmap){
File imagePath = new File("sdcard/screenshot.jpg");
FileOutputStream fos;
try {
fos = new FileOutputStream(imagePath);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
new Thread(new clienthread()).start();
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class clienthread implements Runnable {
#Override
public void run() {
// TODO Auto-generated method stub
try{
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
/*File imagePath = new File("sdcard/screenshot.jpg");
byte[] mybytearray = new byte[450560];
FileInputStream fis = new FileInputStream(imagePath);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = socket.getOutputStream();
os.write(mybytearray,0,mybytearray.length);
os.close();*/
}
catch(Exception e){
}
}
}
}
Here:
new EchoThread(socket).start();
if ( socket != null && !socket.isClosed() ){
try {
socket.close();//Don't do this here!!!!!!
JOptionPane.showMessageDialog(null, "Client Disconnected", "ALERT", JOptionPane.INFORMATION_MESSAGE);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You shouldn't close your socket after you started your Thread. The closing of the socket should be the job of the EchoThread after you finished communicating with it. You can insert this line at the end of run() method socket.close(); so it closes itself when you're done.
Looks like it is most likely due to this line:
if ( socket != null && !socket.isClosed() ){
If your socket was previously opened and you passed if off to the thread to handle, the socket would still be open and socket.isClosed() will return false and you'll immediately close the socket and clean it up in your main thread.
Related
Server : package Server;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import javax.imageio.ImageIO;
public class Server extends Thread{
private ServerSocket mServer_Socket;
private ArrayList<SocketManager> managers = new ArrayList<SocketManager>();
public Server(){
try {
mServer_Socket = new ServerSocket(4242);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
Socket msocket;
try{
msocket = mServer_Socket.accept();
System.out.println("connected");
managers.add(new SocketManager(msocket));
}catch(Exception e){
e.printStackTrace();
}
}
public void SendMessage(String m, int i){
try {
managers.get(i).write(m.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
private class SocketManager{
private OutputStream mout;
private InputStream min;
public SocketManager(Socket socket){
try{
mout = socket.getOutputStream();
min = socket.getInputStream();
}catch (IOException ioe) {
ioe.printStackTrace();
}
startListen();
}
public void write(byte[] data) throws IOException{
mout.write(data);
}
public void startListen(){
new Thread() {
BufferedImage image;
public void run(){
try {
System.out.println("listen..");
while(true){
if((image = ImageIO.read(min)) != null){
while(min.read() != 'y');
System.out.println("received");
mout.write('y');
mout.flush();
Main.drawImage(image);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
}
Client :package Client;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;
import javax.imageio.ImageIO;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamResolution;
import com.github.sarxos.webcam.ds.fswebcam.FsWebcamDriver;
public class Client {
private static List<Webcam> webcams = null;
static Webcam webcam = null;
static {
Webcam.setDriver(new FsWebcamDriver());
}
public static void main(String[] args) {
try {
webcams =(List<Webcam>) Webcam.getWebcams(1000000);
} catch (Exception e) {
e.printStackTrace();
}
for(Webcam device : webcams){
String name;
System.out.println(name = device.getDevice().getName());
//if(name.equals("Logitech HD Webcam C270 1"))
webcam = device;
}
webcam.setViewSize(WebcamResolution.VGA.getSize());
webcam.open();
try{
Socket socket = new Socket("localhost", 4242);
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
byte[] buffer = new byte[10];
while(true){
ImageIO.write(webcam.getImage(), "png", out);
out.flush();
out.write('y');
out.flush();
System.out.println("read");
while(in.read() != 'y');
}
}catch(Exception e){
e.printStackTrace();
}
}
}
This Program works well about 10sec. But after that It doesn't work. Socket is Connected but It doesn't send anything. I guess it doesn't match sync, so I match sync, but it's not work too. I don't have an idea. why It doesn't work. please help. I can't find problem
Your client needs to send the size of transfered image to server prior to sending the image itself, because your server needs to know how long the image is, in order to read it from socket and start receiving the char data coming right after the image.
And since "ImageIO" has no means of specifying the number of bytes supposed to be read from the input stream, you should use InputStream instead.
See the modified code below (I put comments whenever added a new line, everything else is identical with yours):
Server:
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream; //<--- added
import java.io.DataInputStream; //<--- added
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import javax.imageio.ImageIO;
public class Server extends Thread{
private ServerSocket mServer_Socket;
private ArrayList<SocketManager> managers = new ArrayList<SocketManager>();
public Server(){
try {
mServer_Socket = new ServerSocket(4242);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
Socket msocket;
try{
msocket = mServer_Socket.accept();
System.out.println("connected");
managers.add(new SocketManager(msocket));
}catch(Exception e){
e.printStackTrace();
}
}
public void SendMessage(String m, int i){
try {
managers.get(i).write(m.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
private class SocketManager{
private OutputStream mout;
private InputStream min;
private DataInputStream din; //<--- added DataInputStream
public SocketManager(Socket socket){
try{
mout = socket.getOutputStream();
min = socket.getInputStream();
din = new DataInputStream(min); //<--- initialized DataInputStream
}catch (IOException ioe) {
ioe.printStackTrace();
}
startListen();
}
public void write(byte[] data) throws IOException{
mout.write(data);
}
public void startListen()
{
new Thread() {
BufferedImage image;
public void run(){
try {
System.out.println("listen..");
while(true)
{
int arrlen = din.readInt(); //<--- receive image size in order to prepare a buffer for it
byte[] b = new byte[arrlen]; //<--- prepare a buffer
din.readFully(b); //<--- receive image data
while(min.read() != 'y');
mout.write('y');
mout.flush();
InputStream bais = new ByteArrayInputStream(b); //<--- get ByteArrayInputStream from buffer
BufferedImage image = ImageIO.read(bais); //<--- prepare BufferedImage from ByteArrayInputStream
bais.close(); //<--- close ByteArrayInputStream
Main.drawImage(image);
}//end while true
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
}
Client:
import java.awt.image.BufferedImage; //<--- added
import java.io.ByteArrayOutputStream; //<--- added
import java.io.DataOutputStream; //<--- added
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.List;
import javax.imageio.ImageIO;
import com.github.sarxos.webcam.Webcam;
import com.github.sarxos.webcam.WebcamResolution;
import com.github.sarxos.webcam.ds.fswebcam.FsWebcamDriver;
public class Client {
private static List<Webcam> webcams = null;
static Webcam webcam = null;
static {
Webcam.setDriver(new FsWebcamDriver());
}
public static void main(String[] args) {
try {
webcams =(List<Webcam>) Webcam.getWebcams(1000000);
} catch (Exception e) {
e.printStackTrace();
}
for(Webcam device : webcams){
String name;
System.out.println(name = device.getDevice().getName());
//if(name.equals("Logitech HD Webcam C270 1"))
webcam = device;
}
webcam.setViewSize(WebcamResolution.VGA.getSize());
webcam.open();
try{
Socket socket = new Socket("localhost", 4242);
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
DataOutputStream dos = new DataOutputStream(out); //<--- added DataOutputStream
BufferedImage image = null; //<--- added BufferedImage to keep image from webcam
while(true){
ByteArrayOutputStream baos = new ByteArrayOutputStream(); //<--- create ByteArrayOutputStream
image = webcam.getImage(); //<--- get BufferedImage from webcam
ImageIO.write(image, "png", baos); //<--- write image into ByteArrayOutputStream
dos.writeInt(baos.size()); //<--- send image size
dos.flush(); //<--- flush DataOutputStream
baos.close(); //<--- close ByteArrayOutputStream
ImageIO.write(image, "png", out);
out.flush();
out.write('y');
out.flush();
System.out.println("read");
while(in.read() != 'y');
}
}catch(Exception e){
e.printStackTrace();
}
}
}
Backstory:
I created a Barcode Scanning app that can connect with my works server. The Barcode app functions perfectly, however, I have no experience with socket connections to servers. So in order to not mess up any code in the Barcode app I copied a tutorial for a socket connection and edited it. Once I can get the test code to complete a connection and send data back and forth, I will implement it into the Barcode app.
The Problem:
When I click my button that says "Connect to server" I get this:
03-23 11:55:52.174 6438-6459/com.example.vipin.client I/Client: Waiting for message from server...
Pasted below is the code. I have removed the IP address and Port for security reasons.
package com.example.vipin.client;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Client extends AppCompatActivity implements View.OnClickListener {
public static final String TAG = Client.class.getSimpleName();
public static final int SERVERPORT = 0000;
public static final String SERVER_IP = "000.000.0.0";
ClientThread clientThread;
Thread thread;
TextView messageTv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
messageTv = (TextView) findViewById(R.id.messageTv);
}
public void updateMessage(final String message) {
runOnUiThread(new Runnable() {
#Override
public void run() {
messageTv.append(message + "\n");
}
});
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.connect_server) {
messageTv.setText("");
clientThread = new ClientThread();
thread = new Thread(clientThread);
thread.start();
return;
}
if (view.getId() == R.id.send_data) {
clientThread.sendMessage("Hello from Client");
Log.i(TAG, "Sending message to server...");
}
}
class ClientThread implements Runnable {
private Socket socket;
private BufferedReader input;
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
while (!Thread.currentThread().isInterrupted()) {
Log.i(TAG, "Waiting for message from server...");
this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String message = input.readLine();
Log.i(TAG, "Message received from the server : " + message);
if (null == message || "Disconnect".contentEquals(message)) {
Thread.interrupted();
message = "Server Disconnected.";
updateMessage(getTime() + " | Server : " + message);
break;
}
updateMessage(getTime() + " | Server : " + message);
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
void sendMessage(String message) {
try {
if (null != socket) {
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(message);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
String getTime() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
return sdf.format(new Date());
}
#Override
protected void onDestroy() {
super.onDestroy();
if (null != clientThread) {
clientThread.sendMessage("Disconnect");
clientThread = null;
}
}
}
Log for the button click event is here https://pastebin.com/6wbvLj6w
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;
import javax.imageio.ImageIO;
public class ServerPrintScreen
extends Thread {
private ServerSocket serverSocket;
public ServerPrintScreen(int port)
throws IOException, SQLException, ClassNotFoundException, Exception {
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(0);
}
public void run() {
try {
while (true) {
Socket clientSocket = serverSocket.accept();
Throwable localThrowable3 = null;
try {
System.out.println("client connected");
clientSocket.setKeepAlive(true);
String httpResponse = "HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin: *\r\nAccept-Ranges: bytes\r\nContent-Disposition: inline;filename=screenShot.jpg\r\nContent-Type: image/jpg\r\n\r\n";
BufferedImage originalImage = new Robot().createScreenCapture(new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()));
clientSocket.getOutputStream().write(httpResponse.getBytes("UTF-8"));
ImageIO.write(originalImage, "jpg", clientSocket.getOutputStream());
clientSocket.getOutputStream().flush();
clientSocket.getOutputStream().close();
clientSocket.close();
System.out.println("sent");
} catch (Throwable localThrowable1) {
localThrowable3 = localThrowable1;
throw localThrowable1;
} finally {
if (clientSocket != null) {
if (localThrowable3 != null) {
try {
clientSocket.close();
} catch (Throwable localThrowable2) {
localThrowable3.addSuppressed(localThrowable2);
}
} else {
clientSocket.close();
}
}
}
}
} catch (Exception e) {
e.printStackTrace(System.err);
}
}
public static void main(String[] args) throws IOException, SQLException, ClassNotFoundException, Exception {
Thread t = new ServerPrintScreen(25000);
t.start();
}
}
I'm continuing work on an android app for my coworkers. I've gotten past the errors in my code, but a new problem has arisen. The server program is meant to read from a text file and send the data to an android app, which interprets the data and organizes it into a listview.
This is the code:
Bserver:
package beaconserver;
import java.io.*;
import java.net.*;
public class Bserver {
static ServerSocket Sock = null;
static Socket server = null;
public static void main(String[] args) {
BufferedReader in = null;
PrintWriter Out = null;
String ok;
try{
System.out.println("Waiting for connection");
while(true){
Sock = new ServerSocket(8006);
server = Sock.accept();
in = new BufferedReader(new InputStreamReader(server.getInputStream()));
Out = new PrintWriter(server.getOutputStream());
String input = null;
Bfile file = new Bfile();
String[] companies = file.get();
System.out.println("starting send");
while(true){
System.out.println("in the while loop");
ok=in.readLine();
Bprotocol protocol = new Bprotocol();
input = protocol.sendMessage(ok, companies );
Out.write(input);
if(input.equals("end")){
break;
}
}
System.out.println("out of the while loop");
Out.close();
in.close();
server.close();
Sock.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Bprotocol:
public class Bprotocol {
static String output = null;
static int count = 0;
public String sendMessage(String ok, String[] file){
if(ok!=null && count<file.length){
System.out.println(count+1 + "of" + file.length);
output = file[count];
count++;
}else if(ok==null && count<file.length){
output=null;
}else if (count==file.length){
output = "end";
}
return output;
}
}
Bfile:
package beaconserver;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class Bfile {
static String[] filenames;
static BufferedReader Br = null;
static String names = null;
static ArrayList<String> Names = new ArrayList<String>();
public String[] get(){
try {
Br = new BufferedReader(new FileReader("/home/kyle/Documents/names.txt"));
} catch (FileNotFoundException e) {
System.out.println("file not found");
e.printStackTrace();
}
try {
while(Br.ready()){
names = Br.readLine();
Names.add(names);
}
Br.close();
} catch (IOException e) {
System.out.println("IOexception");
e.printStackTrace();
}
filenames = new String[Names.size()];
filenames = Names.toArray(filenames);
return filenames;
}
}
MainActivity: android
package com.AWS.beacon;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity{
TextView response;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
response = (TextView) this.findViewById(R.id.textView2);
new GetNames(this).execute();
}
}
class GetNames extends AsyncTask<Void,String,Void>{
ArrayList<String> names = new ArrayList<String>();
PrintWriter out = null;
BufferedReader in = null;
Socket sock = null;
int L = 0;
String T = null;
static String[] companies = null;
String fromserver;
public MainActivity GetNamescontext =null;
public GetNames (MainActivity context){
GetNamescontext = context;
}
#Override
protected void onPreExecute(){
super.onPreExecute();
TextView prog = (TextView) GetNamescontext.findViewById(R.id.textView2);
prog.setText("Connecting");
}
#Override
protected Void doInBackground(Void... params) {
try {
sock = new Socket("elvishknight1.noip.me", 8006);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
in = new BufferedReader(new InputStreamReader(sock.getInputStream()));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out = new PrintWriter(sock.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.write("ok");
while((fromserver=in.readLine())!=null){
if(fromserver.equals("end")){
break;
}
T = in.readLine();
names.add(T);
}
out.close();
in.close();
sock.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
super.onPostExecute(result);
companies = names.toArray(new String[names.size()]) ;
Intent i = new Intent(GetNamescontext, MainScreen.class);
GetNamescontext.startActivity(i);
}
}
the program has some Sytsem.out.println commands for debugging. the problem is the program gets stuck on "in the while loop" and stops there. No errors, no logcat, nothing. I'm not sure what the problem could be. Could you guys help me out on this.
Thanks
You should add Out.flush() after Out.write(input);
When to use flush method and why do we use it?
this is used when there needs to be synchronous sending
for example you have a duplex (2-way) connection and you just sent a message and now need to wait for the reply on it, without flush a buffered outputstream might hold it until the buffer fills up (deadlock)
Temp Solution : i suppose you have defined in project's manifest that you need the internet permission. See this link
In your client you use readLine(). Therefore the server should write lines. Lines end with a \n. Especially send "end\n".
im trying to send image over socket in android using two emulator, log file give me
05-28 13:55:07.349: I/System.out(26763): Receiving...
and i can see the created image from file explorer in data\files\output.jpg but it's blank and it's size =0k
package com.javacodegeeks.android.androidsocketserver;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.util.Log;
public class Main extends Activity {
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStream inputStream;
private static FileOutputStream fileOutputStream;
private static BufferedOutputStream bufferedOutputStream;
private static int bufferSize = 3000; // bufferSize temporary hardcoded
private static int bytesRead;
private static int totalbytesRead = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
init();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void init() throws IOException {
// TODO Auto-generated method stub
serverSocket = new ServerSocket(6000); // Server socket
System.out.println("Server started. Listening to the port 4444");
clientSocket = serverSocket.accept();
byte[] data = new byte[bufferSize]; // create byte array to buffer the
// file
inputStream = clientSocket.getInputStream();
String filePath = this.getFilesDir().getPath().toString()
+ "/output.jpg";
fileOutputStream = new FileOutputStream(filePath);
// fileOutputStream = new FileOutputStream(file);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
System.out.println("Receiving...");
// following lines read the input slide file byte by byte
bytesRead = inputStream.read(data,0,data.length);
totalbytesRead = bytesRead;
do {
bytesRead =
inputStream.read(data, totalbytesRead, (data.length-totalbytesRead));
if(bytesRead >= 0) totalbytesRead += bytesRead;
} while(bytesRead > -1);
bufferedOutputStream.write(data, 0 , totalbytesRead);
bufferedOutputStream.flush();
long end = System.currentTimeMillis();
System.out.println(end);
bufferedOutputStream.close();
System.out.println("Sever recieved the file");
}
}
and this is client side
package com.javacodegeeks.android.androidsocketclient;
/*
* This is a simple Android mobile client
* This application send any file to a remort server when the
* send button is pressed
* Author by Lak J Comspace
*/
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Transfer extends Activity {
private Socket client;
private FileInputStream fileInputStream;
private BufferedInputStream bufferedInputStream;
private OutputStream outputStream;
private Button button;
private TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transfer);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
button = (Button) findViewById(R.id.button1); // reference to the send
// button
text = (TextView) findViewById(R.id.textView1); // reference to the text
// view
// Button press event listener
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
File file = new File("Desktop:\\test.jpg"); // create file
// instance
client = new Socket("10.0.2.2", 5000);
byte[] mybytearray = new byte[(int) file.length()]; // create
// a
// byte
// array
// to
// file
fileInputStream = new FileInputStream(file);
bufferedInputStream = new BufferedInputStream(
fileInputStream);
outputStream = client.getOutputStream();
int read_count = 0;
while ((read_count = bufferedInputStream.read(mybytearray,
0, mybytearray.length)) != -1) {
outputStream.write(mybytearray, 0, read_count); // Now
// writes
// the
// correct
// amount
// of
// bytes
outputStream.flush();
}
outputStream.flush();
bufferedInputStream.close();
outputStream.close();
client.close();
text.setText("File Sent");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
Remove the first inputStream.read() as there you read the whole filecontents already but throw it away. There is nothing more to read the second time.
I have a problem with readLine() in Java. I have a server and a client. From client I want to send a message to the server. The problem is that first, the client has to insert a text into a JTextField and when presses send then server to read the input from client, but server doesn't wait the input from client but instead reads null. But I read that readLine() is blocked until it has something to read, why it's not happening in this case?
Here I connect to the server and create the JFrame
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class StartingPoint {
private static PrintWriter out;
private static BufferedReader in;
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
try {
connectToServer();
createAndShowGui();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
public static void createAndShowGui() throws IOException {
View frame = new View(out, in);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void connectToServer() throws IOException {
String serverAddress = "127.0.0.1";
int PORT = 8100;
Socket clientSocket = null;
out = null;
in = null;
try {
clientSocket = new Socket(serverAddress, PORT);
out = new PrintWriter(clientSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Could not connect to the server \n" + e);
System.exit(1);
} finally {
if (out != null)
out.close();
if (in != null)
in.close();
if (clientSocket != null)
clientSocket.close();
}
}
}
Here is JFrame implementation:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class View extends JFrame {
private JButton button;
private JTextField field;
private JPanel gui;
public View(final PrintWriter out, final BufferedReader in) throws IOException {
button = new JButton("Send");
field = new JTextField();
gui = new JPanel(new GridLayout(1, 0, 10, 10));
gui.add(button);
gui.add(field);
add(gui);
button.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
out.println(field.getText());
try {
System.out.println(in.readLine());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
Here is the server:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleServer extends Thread {
public static final int PORT = 8100;
private static ServerSocket serverSocket = null;
private Socket clientSocket = null;
public void run() {
String receive, answer;
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
clientSocket.getInputStream()));
PrintWriter out = new PrintWriter(clientSocket.getOutputStream());
receive = in.readLine();
System.out.println("[server]" + receive);
answer = "hello " + receive;
out.println(answer);
out.flush();
} catch (IOException e) {
System.err.println("IO error \n" + e);
} finally {
try {
clientSocket.close();
} catch (IOException e) {
System.err.println("Close socket error \n" + e);
}
}
}
public SimpleServer() throws IOException {
while (true) {
serverSocket = new ServerSocket(PORT);
try {
clientSocket = serverSocket.accept();
new Thread(this).start();
} finally {
serverSocket.close();
}
}
}
public static void main(String[] args) throws IOException {
SimpleServer server = new SimpleServer();
}
}
Your connectToServer() method opens a connection, creates streams and ... then closes them before returning. So of course, the server sees the close straight away, and returns null on the first readLine() call.
I suspect that you may have copied the "close in a finally block" pattern without understanding what it means. So I shall explain:
This is the normal pattern:
InputStream is = null;
try {
is = new FileInputStream(someFile);
// read the stream
} finally {
if (is != null) {
is.close();
}
}
The purpose of the code above is to ensure that the InputStream is always closed. Or more precisely, that it is always closed before the try/finally exits.
This is generally a good thing. But if the purpose of your code is to open some streams that is going to be used after this bit of code completes, then closing the stream here is self defeating.
InputStream is = null;
try {
is = new FileInputStream(someFile);
} finally {
if (is != null) {
is.close();
}
}
// read the stream ... OOOPS! We've already closed it!!
So to take this back to your original code, you need to move the try/finally/close stuff to the run method, something along these lines:
public void run() {
try {
connectToServer();
createAndShowGui();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out != null)
out.close();
if (in != null)
in.close();
if (clientSocket != null)
clientSocket.close();
}
}
You should also catch and (probably) ignore IOException that might be thrown by each close() call.
Javadoc for BufferedReader.readLine()
doesn't say anything like that:
Returns:
A String containing the contents of the line, not including
any line-termination characters, or null if the end of the stream has been reached
In your code you are opening a connection in connectToServer() and closing it, so server sees the end of stream