Chat along with another data sending in socket programming android - android

I'm developing a project where client sends screenshots of its activity to server where the bitmap is converted to string.For me it works well.I would like to add a chat between client and server in this project.How can I achieve this?Any kind of help is accepted.
Client Code
public class Client2 extends AsyncTask<Void, Void, Void> {
public static String dstAddress;
int dstPort;
String response= new String() ;
String msg_server=new String();
Context context;
public static ArrayList<Bitmap>ss=new ArrayList<>();
public static Socket socket;
Client2(Context ic,String addr, int port,String msg) {
context=ic;
dstAddress = addr;
dstPort = port;
msg_server=msg;
}
#Override
protected Void doInBackground(Void... arg0) {
socket = null;
ObjectOutputStream dataOutputStream = null;
ObjectInputStream dataInputStream = null;
try {
socket = new Socket(dstAddress, dstPort);
dataOutputStream = new ObjectOutputStream(
socket.getOutputStream());
dataInputStream = new ObjectInputStream(socket.getInputStream());
if(msg_server != null){
dataOutputStream.writeObject(msg_server);
dataOutputStream.flush();
}
response = (String) dataInputStream.readObject();
} 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();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try { socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Toast.makeText(context, response, Toast.LENGTH_SHORT).show();
}}
Server Code
public class Server extends Thread{
ServerSocket serverSocket;
Viewer activity;
static final int SocketServerPORT = 8080;
int count = 0;
int sc=0;
Bitmap bmviewer;
String msgtoclient,msgfromclient;
ArrayList<Bitmap>ser=new ArrayList<>();
public Server(Activity context,String msg )
{
activity= (Viewer) context;
msgtoclient=msg;
}
#Override
public void run() {
Socket socket = null;
ObjectInputStream dataInputStream = null;
ObjectOutputStream dataOutputStream = null;
try {
// serverSocket = new ServerSocket(SocketServerPORT);
serverSocket = new ServerSocket(); // <-- create an unbound socket first
serverSocket.setReuseAddress(true);
serverSocket.bind(new InetSocketAddress(SocketServerPORT));// serverSocket.setReuseAddress(true);
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Viewer.demo.setText("Port No: "
+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
dataInputStream = new ObjectInputStream(
socket.getInputStream());
dataOutputStream = new ObjectOutputStream(
socket.getOutputStream());
String messageFromClient = new String();
//If no message sent from client, this code will block the program
messageFromClient = (String) dataInputStream.readObject();
count++;
bmviewer = (stringtobitmap(messageFromClient));
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//Viewer.demo.setText(message);
sc++;
saveimage(bmviewer, sc);
// Viewer.images.setImageBitmap(bmviewer);
Viewer.imageGallery.addView(getImageView(bmviewer));
}
});
if (msgtoclient.equals("")){
String reply="received";
dataOutputStream.writeObject(reply);
dataOutputStream.flush();}
else {
dataOutputStream.writeObject(msgtoclient);
dataOutputStream.flush();
}
}
}catch(EOFException e){
e.printStackTrace();
final String errMsg = e.toString();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Snackbar snackbar=Snackbar.make(Viewer.relativeLayout,errMsg,Snackbar.LENGTH_LONG);
snackbar.show();
}
});
} catch(IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
final String errMsg = e.toString();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Snackbar snackbar=Snackbar.make(Viewer.relativeLayout,errMsg,Snackbar.LENGTH_LONG);
snackbar.show();
}
});
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private View getImageView(Bitmap image) {
ImageView imageView = new ImageView(activity);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.setMargins(0, 0, 10, 0);
imageView.setLayoutParams(lp);
imageView.setImageBitmap(image);
return imageView;
}
private void saveimage(Bitmap bmp,int c) {
sc=c;
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/screenshare_viewer");
myDir.mkdirs();
//Random generator = new Random();
// int n = 10000;
// n = generator.nextInt(n);
String fname = "Image-"+sc +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private Bitmap stringtobitmap(String message) {
try{
byte [] encodeByte= Base64.decode(message,Base64.DEFAULT);
Bitmap bitmap= BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
return bitmap;
}
catch(Exception e){
e.getMessage();
return null;
}
}
}

Related

Send an image through socket: ByteArrayOutputStream.size() return negative value (sometimes )

I am making server-client program, the server is Java on the computer and the client is android app (android studio) and I try to send image from the server to the client, and to show this image on the client's screen by ImageView. The problem is that sometimes its work and sometimes it doesn't work. Looks like there are times that ByteArrayOutputStream.size() return negative value in the client side in the variable len (that keep the length). When the return value is positive it works. Why am I getting negative values (sometimes)?
Server code:
public class Server extends JFrame {
BufferedImage bi,inputImage;
JButton btn;
ServerSocket serverSocket;
Socket socket;
private Scanner in;
private PrintWriter out;
public Server(){
File imageFile = new File("ssss.PNG");
try {
bi = ImageIO.read(imageFile);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
this.add(btn = new JButton("Send"), BorderLayout.NORTH);
this.add(new JLabel(new ImageIcon(bi)), BorderLayout.CENTER);
this.setSize(200, 180);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
try{
serverSocket = new ServerSocket(8000);
socket = serverSocket.accept();
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream(), true);
}
catch(IOException ex){
System.err.println(ex);
}
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
out.println("IMAGE");
sendImage(new File("ssss.PNG"));
// try {
// ImageIO.write(bi, "PNG", socket.getOutputStream());
//} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
// }
}
});
}
public static void main(String[] args) {
new Server();
}
public void sendImage(File file){
try {
DataOutputStream out = new DataOutputStream(
socket.getOutputStream());
DataInputStream dis = new DataInputStream(new FileInputStream(file));
ByteArrayOutputStream ao = new ByteArrayOutputStream();
int read = 0;
byte[] buf = new byte[dis.available()];
while ((read = dis.read(buf)) > -1) {
ao.write(buf, 0, read);
}
System.out.println("ao.size(): "+ao.size());
out.writeInt(ao.size());
out.write(ao.toByteArray());
out.flush();
// out.close();
// dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client code(android):
public class MainActivity extends AppCompatActivity {
public Socket socket;
public PrintWriter out;
public Scanner in;
public TextView textView;
public DataOutputStream dos=null;
public DataInputStream dis=null;
public ImageView imageView;
public Bitmap bitmap;
private static final int SERVERPORT = 8000;
private static final String SERVER_IP = "192.168.5.59";
public static final String TAG="TAG";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView)findViewById(R.id.text);
imageView=(ImageView)findViewById(R.id.imageView);
imageView.setImageResource(R.drawable.ic_launcher_background);
new Thread(new ClientThread()).start();
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
Log.d(TAG, "try to connect...");
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream(), true);
Log.d(TAG, "connected1234");
while (in.hasNextLine()) {
String response = in.nextLine();
if (response.startsWith("IMAGE")) {
InputStream in = socket.getInputStream();
Log.d(TAG, "in: "+in);
DataInputStream input = new DataInputStream(in);
Log.d(TAG, "input: "+input);
byte[] data;
int len= input.readInt();
Log.d(TAG, "len: "+len);
data = new byte[len];
Log.d(TAG, "data: "+data);
if (len > 0) {
input.readFully(data,0,data.length);
}
final Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data .length);
Log.d(TAG, "Bitmap: "+bitmap);
runOnUiThread(new Runnable() {
#Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
}
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
The error:
len: -298696669
E/AndroidRuntime: FATAL EXCEPTION: Thread-5
Process: com.example.sendimageexample, PID: 17224
java.lang.NegativeArraySizeException: -298696669
at com.example.sendimageexample.MainActivity$ClientThread.run(MainActivity.java:80)
at java.lang.Thread.run(Thread.java:784)`
I solved it!
client code:
public class MainActivity extends AppCompatActivity {
public Socket socket;
public ImageView imageView;
private static final int SERVERPORT = 8000;
private static final String SERVER_IP = "192.168.5.59";
public static final String TAG="TAG";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView=(ImageView)findViewById(R.id.imageView);
imageView.setImageResource(R.drawable.ic_launcher_background);
new Thread(new ClientThread()).start();
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
Log.d(TAG, "try to connect...");
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
Log.d(TAG, "Adder: "+serverAddr);
socket = new Socket(serverAddr, SERVERPORT);
InputStream in = socket.getInputStream();
Log.d(TAG, "in: "+in);
DataInputStream input = new DataInputStream(in);
Log.d(TAG, "input: "+input);
Log.d(TAG, "connected1234");
byte[] data;
int len= input.readInt();//-298696669//17976
Log.d(TAG, "len: "+len);
data = new byte[len];
Log.d(TAG, "data: "+data);
if (len > 0) {
input.readFully(data,0,data.length);
}
final Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data
.length);
Log.d(TAG, "Bitmap: "+bitmap);
runOnUiThread(new Runnable() {
#Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
ByteArrayOutputStream bos =new ByteArrayOutputStream();
Bitmap bitmap1=BitmapFactory.decodeResource(getResources(),R.drawable.image22);
Log.d(TAG, "bitmap1: "+bitmap1);
bitmap1.compress(Bitmap.CompressFormat.PNG,0,bos);
byte []array=bos.toByteArray();
OutputStream outputStream=socket.getOutputStream();
DataOutputStream dos=new DataOutputStream(outputStream);
dos.writeInt(bos.size());
dos.write(array,0,array.length);
Log.d(TAG, "bos.size: "+bos.size());
Log.d(TAG, "bos.array: "+bos.toByteArray());
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
server code:
public class Server extends JFrame {
BufferedImage bi,inputImage;
JButton btn;
ServerSocket serverSocket;
Socket socket;
private Scanner in;
private PrintWriter out;
Server jframe=this;
public Server(){
File imageFile = new File("ssss.PNG");
try {
bi = ImageIO.read(imageFile);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
this.add(btn = new JButton("Send"), BorderLayout.NORTH);
//this.add(new JLabel(new ImageIcon(bi)), BorderLayout.CENTER);
this.setSize(200, 180);
this.setVisible(true);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setLocationRelativeTo(null);
try{
serverSocket = new ServerSocket(8000);
socket = serverSocket.accept();
in = new Scanner(socket.getInputStream());
out = new PrintWriter(socket.getOutputStream(), true);
}
catch(IOException ex){
System.err.println(ex);
}
btn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
sendImage(new File("ssss.PNG"));
InputStream inputStream;
try {
inputStream = socket.getInputStream();
DataInputStream dis=new DataInputStream(inputStream);
int size = dis.readInt();
System.out.println("size: "+size);
byte[] imageAr = new byte[size];
dis.readFully(imageAr);
System.out.println("imageAr: "+imageAr);
System.out.println("dis: "+dis);
BufferedImage image = ImageIO.read(new ByteArrayInputStream(imageAr));
jframe.add(new JLabel(new ImageIcon(image)), BorderLayout.CENTER);
revalidate();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// try {
// ImageIO.write(bi, "PNG", socket.getOutputStream());
//} catch (IOException e) {
// TODO Auto-generated catch block
// e.printStackTrace();
// }
}
});
}
public static void main(String[] args) {
new Server();
}
public void sendImage(File file){
try {
DataOutputStream out = new DataOutputStream(
socket.getOutputStream());
DataInputStream dis = new DataInputStream(new FileInputStream(file));
ByteArrayOutputStream ao = new ByteArrayOutputStream();
int read = 0;
byte[] buf = new byte[dis.available()];
while ((read = dis.read(buf)) > -1) {
ao.write(buf, 0, read);
System.out.println("read: "+read);
System.out.println("buf: "+buf);
}
System.out.println("ao.size(): "+ao.size());
out.writeInt(ao.size());
System.out.println("ao.toByteArray(): "+ao.toByteArray());
out.write(ao.toByteArray());
out.flush();
// out.close();
// dis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Socket client - server(android)

Sorry for my english. I am trying to create client and server. Now, my logic is like this:
I start app -> start server -> server listening to all messages -> if client sends message to server -> message goes to server -> message received by server -> server needs to send a message to all its customers.
But the server does not do this
** the server needs to send a message to all its customers**
or maybe
the client is not listening to the server.
my question: Why does the client not accept messages from the server?
//Main
//send message
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (sendText.getText().toString().equals("")) {
return;
}
if(chatClientThread==null){
return;
}
chatClientThread.sendMsg(sendText.getText().toString() + "\n");
}
});
//method create server and client, cliend connect to server
createServer(port);
}
public void createServer(int port) {
//create server
ChatServerThread chatServerThread = new ChatServerThread(port);
chatServerThread.start();
//subscribe to server 192.168.31.101 - ip server
createClient("Testov", "192.168.31.101", port);
}
//method for create client
public void createClient(String name, String ipAdress, int SocketServerPORT) {
chatClientThread = new ChatClientThread(
name, ipAdress, SocketServerPORT);
chatClientThread.start();
}
//this is server class
private class ChatServerThread extends Thread {
int SocketServerPORT;
public ChatServerThread(int SocketServerPORT) {
//set port
this.SocketServerPORT = SocketServerPORT;
}
#Override
public void run() {
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
//create server socket
serverSocket = new ServerSocket(SocketServerPORT);
//waite connect
socket = serverSocket.accept();
Log.e("connect", "server side");
//for input and output
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
//listener
while(true) {
if (dataInputStream.available() > 0) {
//read line
String newMsg = dataInputStream.readUTF();
//send line to client
dataOutputStream.writeUTF(newMsg);
final String ms = newMsg;
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), ms, Toast.LENGTH_SHORT).show();
}
});
//end thread
dataOutputStream.flush();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
//this is client side
private class ChatClientThread extends Thread {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
String name;
String dstAddress;
int dstPort;
String msgToSend = "";
boolean goOut = false;
String msgLog = "";
ChatClientThread(String name, String address, int port) {
this.name = name;
dstAddress = address;
dstPort = port;
}
#Override
public void run() {
try {
//set ip adress and port
socket = new Socket(dstAddress, dstPort);
//for get and post data
String mesageFromServer = null;
dataInputStream = new DataInputStream(socket.getInputStream());
while(!goOut) {
//wait message from server
mesageFromServer = dataInputStream.readUTF();
//output
Log.e("client", mesageFromServer);
final String ms = mesageFromServer;
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), ms, Toast.LENGTH_SHORT).show();
}
});
msgToSend = "";
}
} catch (UnknownHostException e) {
e.printStackTrace();
final String eString = e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, eString, Toast.LENGTH_LONG).show();
Log.e("errror", eString);
}
});
} catch (IOException e) {
e.printStackTrace();
final String eString = e.toString();
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, eString, Toast.LENGTH_LONG).show();
Log.e("errror", eString);
}
});
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private void sendMsg(String msg){
try {
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
private void disconnect(){
goOut = true;
}
}

Searching the Server IP on Client instead of inputing

Server: PC
Client: Android
So my Client/Server app consists in opening webpages and executing a bot, everything is fine if I use only for a router, but I would like to be able to to connect in different places (different router/PC).
I was searching for "Wi-fi Search of IP" and got nothing.
Is it possible to give to the Server side a fix IP? like always 192.168.1.68?
Client Code
public class AndroidClient extends Activity
{
EditText episode;
Spinner spinner1;
String result;
Button buttonConnect, buttonClear;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
episode = (EditText) findViewById(R.id.episode);
buttonConnect = (Button) findViewById(R.id.connect);
buttonClear = (Button) findViewById(R.id.clear);
spinner1 = (Spinner) findViewById(R.id.Animes);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.Anime, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
addListenerOnSpinnerItemSelection();
addListenerOnButton();
}
public void addListenerOnSpinnerItemSelection() {
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.Animes);
buttonConnect = (Button) findViewById(R.id.connect);
buttonConnect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
MyClientTask myClientTask = new MyClientTask();
myClientTask.execute();
}
});
}
public class MyClientTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket("10.1.3.68", 8080);
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(episode.getText() + "-" + String.valueOf(spinner1.getSelectedItem()));
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} 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();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
}
}
}
Server Code
public class ServerSide extends Application
{
TextField textTitle;
Label labelSys, labelPort, labelIp;
Label labelMsg;
CheckBox optWelcome;
ServerSocket serverSocket;
String message = "";
String result;
#Override
public void start(Stage primaryStage) {
textTitle = new TextField();
labelSys = new Label();
labelPort = new Label();
labelIp = new Label();
labelMsg = new Label();
labelIp.setText(getIpAddress());
VBox mainLayout = new VBox();
mainLayout.setPadding(new Insets(5, 5, 5, 5));
mainLayout.setSpacing(5);
mainLayout.getChildren().addAll(textTitle,
labelSys, labelPort, labelIp,
labelMsg);
StackPane root = new StackPane();
root.getChildren().add(mainLayout);
Scene scene = new Scene(root, 300, 400);
primaryStage.setTitle("One Piece");
primaryStage.setScene(scene);
primaryStage.show();
Thread socketServerThread = new Thread(new SocketServerThread());
socketServerThread.setDaemon(true);
socketServerThread.start();
}
public static void main(String[] args) {
launch(args);
}
private class SocketServerThread extends Thread {
static final int SocketServerPORT = 8080;
int count = 0;
#Override
public void run() {
try {
Socket socket = null;
serverSocket = new ServerSocket(SocketServerPORT);
Platform.runLater(new Runnable() {
#Override
public void run() {
labelPort.setText("I'm waiting here: "
+ serverSocket.getLocalPort());
}
});
while (true) {
socket = serverSocket.accept();
count++;
//Start another thread
//to prevent blocked by empty dataInputStream
Thread acceptedThread = new Thread(
new ServerSocketAcceptedThread(socket, count));
acceptedThread.setDaemon(true); //terminate the thread when program end
acceptedThread.start();
}
} catch (IOException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
private class ServerSocketAcceptedThread extends Thread {
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
int count;
ServerSocketAcceptedThread(Socket s, int c) {
socket = s;
count = c;
}
#Override
public void run() {
try {
dataInputStream = new DataInputStream(
socket.getInputStream());
dataOutputStream = new DataOutputStream(
socket.getOutputStream());
//If dataInputStream empty,
//this thread will be blocked by readUTF(),
//but not the others
String messageFromClient = dataInputStream.readUTF();
message += "#" + count + " from " + socket.getInetAddress()
+ ":" + socket.getPort() + "\n"
+ "Msg from client: " + messageFromClient + "\n";
Platform.runLater(new Runnable() {
#Override
public void run() {
labelMsg.setText(message);
}
});
String string = messageFromClient;
String[] parts = string.split("-");
String episode = parts[0];
String anime = parts[1];
String OneP = new String("One Piece");
String Naruto = new String ("Naruto");
String Bleach = new String ("Bleach");
int EPnumb = Integer.parseInt(episode);
if (EPnumb < 10) {
result = "00" + episode;
}
else if (EPnumb < 100 && EPnumb >= 10) {
result = "0" + episode;
}
else { result = episode; }
if (anime.equals(OneP)){
try {
Desktop desktop = java.awt.Desktop.getDesktop();
URI oURL = new URI("http://kissanime.com/Anime/One-Piece/Episode-"+ result);
desktop.browse(oURL);
} catch (Exception e) {
e.printStackTrace();
}}
else {
try {
Desktop desktop = java.awt.Desktop.getDesktop();
URI oURL = new URI("http://kissanime.com/Anime/Naruto-Shippuuden/Episode-"+result);
desktop.browse(oURL);
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (IOException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
private java.lang.String parseInt(java.lang.String episode) {
// TODO Auto-generated method stub
return null;
}
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 ex) {
Logger.getLogger(ServerSide.class.getName()).log(Level.SEVERE, null, ex);
}
return ip;
}
public DataInputStream String(String string) {
return null;
}
}
You can use ServerSocket(int port, int backlog, InetAddress bindAddr)
Constructs a new ServerSocket instance bound to the given localAddress and port.

I m not receiving real time stream because receivePacket is the most 1024 bytes

i want to do real time stream from my pc to android device with WIFI. Server code is written by Java. My codes is running true. when I clicked the button in android, in server, sendPacket is actived and it sends packet. I send 65000 bytes(sendPacket) from server, but client receive is 1024 bytes(receivePacket). that' s problem. If sendPacket is smaller, view is very bad.Thank you for your helps...
main.java(server)
public class main {
private static JFrame jframeImage;
private static FacePanel panelImage;
public static DatagramSocket socket;
private static ThreadSender threadSender;
public static void main(String[] args) {
try {
socket = new DatagramSocket(Constants.PORT_ADDRESS);
} catch (SocketException e) {
e.printStackTrace();
}
threadSender = new ThreadSender(socket);
threadSender.start();
initFrame();
System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
VideoCapture camFeed = new VideoCapture(0);
Mat matCamFeed = new Mat();
Mat matSender = new Mat();
byte[] clientInformation = new byte[10];
DatagramPacket packetClientInf = null;
try {
System.out.println("Client Bekleniyor....");
packetClientInf = new DatagramPacket(clientInformation,
clientInformation.length);
socket.receive(packetClientInf);
System.out.println("Client baglandi.");
} catch (IOException e1) {
e1.printStackTrace();
}
Constants.IP_ADDRESS = packetClientInf.getAddress();
Constants.CLIENT_PORT = packetClientInf.getPort();
System.out.println("client ip:"+packetClientInf.getAddress());
System.out.println("client port: "+packetClientInf.getPort());
String s = new String(packetClientInf.getData());
System.out.println("gelen data: "+s);
while (true) {
camFeed.read(matCamFeed);
Imgproc.resize(matCamFeed, matSender, new Size(150, 150));
BufferedImage bufImage = null;
try {
bufImage = matToBufferedImage(matSender);
} catch (IOException e) {
e.printStackTrace();
}
threadSender.setBufImageForSend(bufImage);
threadSender.run();
panelImage.setImage(bufImage);
panelImage.repaint();
}
}
public static void initFrame() {
jframeImage = new JFrame("Image from client");
jframeImage.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframeImage.setSize(400, 400);
jframeImage.setVisible(true);
JButton btnGonder = new JButton("gonder");
btnGonder.setVisible(true);
panelImage = new FacePanel();
jframeImage.setContentPane(panelImage);
}
public static BufferedImage matToBufferedImage(Mat mat) throws IOException {
MatOfByte bytemat = new MatOfByte();
Highgui.imencode(".jpg", mat, bytemat);
byte[] bytes = bytemat.toArray();
InputStream in = new ByteArrayInputStream(bytes);
BufferedImage img = ImageIO.read(in);
return img;
}
}
ThreadSender.java
public class ThreadSender extends Thread {
private BufferedImage bufImageForSend;
private DatagramSocket socket;
public ThreadSender(DatagramSocket socket) {
this.socket = socket;
bufImageForSend = null;
}
public void setBufImageForSend(BufferedImage bufImageForSend) {
this.bufImageForSend = bufImageForSend;
}
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
if (bufImageForSend != null) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(bufImageForSend, "jpeg", bos);
} catch (Exception e) {
// TODO: handle exception
}
byte[] byteImage = bos.toByteArray();
System.out.println("Total image byte length: " + byteImage.length);
if (byteImage.length <= 65500) {
DatagramPacket packet = new DatagramPacket(byteImage,
byteImage.length, Constants.IP_ADDRESS, Constants.CLIENT_PORT);
try {
socket.send(packet);
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
}
}
Client.java
public class MainActivity extends ActionBarActivity {
EditText messageEdit;
Button sendButton;
TextView informationText;
ImageView image;
CheckBox devam;
int PORT=999;
InetAddress IPAddress;
String serverHostname = new String("172.28.8.44");
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendButton = (Button) findViewById(R.id.button1);
messageEdit = (EditText) findViewById(R.id.editText1);
image = (ImageView) findViewById(R.id.imageView1);
devam = (CheckBox) findViewById(R.id.checkbox);
try {
IPAddress = InetAddress.getByName(serverHostname);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sendButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
DatagramSocket clientSocket = null;
try {
clientSocket = new DatagramSocket();
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String sentence = messageEdit.getText()
.toString();
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(
sendData, sendData.length, IPAddress,
PORT);
try {
clientSocket.send(sendPacket);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DatagramPacket receivePacket = new DatagramPacket(
receiveData, receiveData.length);
try {
clientSocket.receive(receivePacket);
byte[] b = receivePacket.getData();
ByteArrayInputStream ba=new ByteArrayInputStream(b);
BufferedInputStream bi=new BufferedInputStream(ba);
final Bitmap bitmap = BitmapFactory
.decodeStream(bi);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
image.setImageBitmap(bitmap);
image.invalidate();
}
});
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
// TODO Auto-generated method stub
}
});
}
}

Why DataOutputStream loses a character?

I have a simple connection activity:
package com.example.conn08;
import ...;
public class MainActivity extends Activity
{
public static Socket clientSocket;
public static DataOutputStream outToServer;
public static PrintWriter outTest;
public static BufferedReader inToServer;
With PrintWriter outTest I test server's availability:
If the user has no Internet, or the server doesn't work, I put Thread on a pause with Boolean shouldContinue.
private Thread mThread;
private final Object lock = new Object();
private Boolean shouldContinue = true;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mThread = new Thread(new Runnable()
{
public void run()
{
while (true)
{
synchronized(lock)
{
try
{
lock.wait(); // lock the Thread
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
while (shouldContinue)
{
try
{
final String data = inToServer.readLine();
if (data != null)
{
Log.v("data", data);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
String put[] = data.split("#");
//Data parsing
}
});
}
}
catch (IOException e)
{
e.printStackTrace();
}
Check on availability of the server:
try {
if(clientSocket.getInputStream().read() == -1)
{
Log.v("Connection: ", "lost");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
mThread.start();
Connect();
}
public void Connect()
{
shouldContinue = true;
try
{
clientSocket = new Socket();
clientSocket.connect(new InetSocketAddress("localhost", 15780), 30000);
outToServer = new DataOutputStream(clientSocket.getOutputStream());
inToServer = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
outTest = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(clientSocket.getOutputStream())), true);
synchronized(lock)
{
lock.notify();
}
sendUTF("3#kokoko"); //send the message!
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void sendUTF(String str)
{
try
{
byte[] buf = str.getBytes("UTF-8");
outToServer.write(buf, 0, buf.length);
outToServer.writeBytes("\n");
outToServer.flush();
}
catch (IOException e)
{
e.printStackTrace();
outServ.setText("Нет соединения!");
}
}
}
Problem in that when I don't use the
if(clientSocket.getInputStream().read() == -1)
And send data to server like here:
sendUTF("3#kokoko");
All is fine, but if I use it, on server I see this message like
"#kokoko" - I lose the first character of the message and my socket is crushed! Help me please

Categories

Resources