indexoutofboundsexception by sending pictures over Socket - java

I want to make a little programm that makes a live-stream for Desktop.
It should be so that you send pictures to an echo-server and he response it to the clients.
There you get be draw the Images. Side by Side. And so it is like a movie(or something like that).
But I always get an indexoutofboundsexception. Where is the error or how can I improve my program.
The ImageIO.write lines thows the Error
//Client Main
public class Main {
public static void main(String[] args) {
Frame frm = new Frame();
Frame.Client client;
frm.setLayout(null);
frm.setDefaultCloseOperation(Frame.EXIT_ON_CLOSE);
frm.setResizable(false);
frm.setSize(1600,900);
frm.setVisible(true);
}
}
// get and send the Desktopimage
public class desktopCapture {
Robot robo;
BufferedImage screenImage;
Rectangle bounding;
public desktopCapture() {
try {
bounding = new Rectangle(0,0,1600,900);
robo = new Robot();
} catch (AWTException e) {e.printStackTrace();}
}
public void sendScreenCapture(Socket client) {
screenImage = robo.createScreenCapture(bounding);
try {
ImageIO.write(screenImage, "png", client.getOutputStream());
} catch (IOException e) {e.printStackTrace();}
}
}
// in Frame two function for actionListener Objects, so I can say who streams his Desktop and which get only the Images to.
public void readImage() {
while(true) {
try {
while((screenImage = ImageIO.read(in)) != null){
repaintScreen();
}
} catch (IOException e) {e.printStackTrace();}
}
}
public void sendImage() {
try {
while(true){
dC.sendScreenCapture(client);
System.out.println("read1");
while((screenImage = ImageIO.read(in)) != null){
System.out.println("read2");
ImageIO.write(screenImage, "png", new File("image1.png"));
Thread.sleep(250);
}
repaintScreen();
screenImage = null;
}
} catch (IOException | InterruptedException e) {e.printStackTrace();}
}
}
}
//Thread for a Client
public class handler implements Runnable {
Socket client;
OutputStream out;
InputStream in;
PrintWriter writer;
BufferedImage image;
public handler(Socket client) {
this.client = client;
}
#Override
public void run() {
try {
in = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
while(true) {
System.out.println("write1");
while((image = ImageIO.read(in)) != null){
System.out.println("write2");
for(int i = 1;i <= Server.connectionArray.size();i++){
Socket TEMP_SOCK = (Socket)Server.connectionArray.get(i-1);
out = TEMP_SOCK.getOutputStream();
writer = new PrintWriter(out);
ImageIO.write(image, "png", TEMP_SOCK.getOutputStream());
System.out.println("write3");
}
image = null;
}
}
} catch (IOException e) {e.printStackTrace();}
}
}

I would change your for loop to:
int count = Server.connectionArray.size()
int index = count - 1;
for(int i = 0;i < count; i++){
Socket TEMP_SOCK = (Socket)Server.connectionArray.get(index);
out = TEMP_SOCK.getOutputStream();
writer = new PrintWriter(out);
ImageIO.write(image, "png", TEMP_SOCK.getOutputStream());
System.out.println("write3");
}

Related

JAVA Socket object + text

Does it possible, to get from client and
objetObjectInputStream
and
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
for example, some client send me tet message, and someone send files. Should I make a new socket server for each?
public class ServerRequests {
Connection con = new Connection();
private Socket socket;
private BufferedReader in;
private BufferedWriter out;
public ServerRequests(Socket socket) throws IOException {
this.socket = socket;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
run();
}
public void run() {
String word;
try {
String object;
ObjectInputStream obIn = new ObjectInputStream(socket.getInputStream());
while ((object = (String) obIn.readObject()) != null){
if (object.contains("F47S")){
String[] result = object.split(":");
String fileName = result[1];
String url = result[2];
String culture = result[3];
System.out.println("FileName:" +fileName);
System.out.println("url:" +url);
FileOutputStream outOb = null;
if(culture.contains("test")) {
outOb = new FileOutputStream(fileName);
}
DataInputStream inOb = new DataInputStream(socket.getInputStream());
byte[] bytes = new byte[5*1024];
int count, total=0;
long lenght = inOb.readLong();
while ((count = inOb.read(bytes)) > -1) {
total+=count;
outOb.write(bytes, 0, count);
if (total==lenght) break;
}
outOb.close();
}
}
}catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
// while (true) {
word = in.readLine();
System.out.println(word);
if (word != null) {
String[] result = word.split(":");
String type = result[0];
if (type.contains("AUTH")) {
String login = result[2];
String pass = result[4];
String gui = con.checkLogin(pass, login);
auth(gui);
}
} catch (IOException e) {
}
}
private void auth(String gui) {
try {
out.write(gui + "\n");
out.flush();
} catch (IOException ignored) {
}
}
private void success(String status) {
try {
out.write(status+ "\n");
out.flush();
} catch (IOException ignored) {
}
}
}

android.os.NetworkOnMainThreadException but my class extends Thread

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

Java Voice Chat Error

I am making a voice chat program. I have two servers one for voice and one for messages. When I connect two people I get this error, Thank you in advance. I attached the client code, ClientAudio code and the Client receive code
java.io.StreamCorruptedException: invalid type code: 00
at java.io.ObjectInputStream$BlockDataInputStream.readBlockHeader(ObjectInputStream.java:2508)
at java.io.ObjectInputStream$BlockDataInputStream.refill(ObjectInputStream.java:2543)
at java.io.ObjectInputStream$BlockDataInputStream.read(ObjectInputStream.java:2702)
at java.io.ObjectInputStream.read(ObjectInputStream.java:865)
at client.chat$ClientAudioRec.run(chat.java:388)
at java.lang.Thread.run(Thread.java:745)
its calling the error on
try {
bytesRead = ((ObjectInput) i2).read(inSound, 0, inSound.length);
} catch (Exception e) {
e.printStackTrace();
}
Code
public class Client implements Runnable { // CLIENT
private String msg;
public void run() {
try {
s1 = new Socket(ipAddress, port);
s2 = new Socket(ipAddress, 1210);
o1 = new ObjectOutputStream(s1.getOutputStream());
o1.writeObject(name);
serverListModel.addElement(name);
i1 = new ObjectInputStream(s1.getInputStream());
Thread voice = new Thread(new ClientAudio());
voice.start();
while(true) {
msg = (String) i1.readObject();
String[] namePart = msg.split("-");
if(namePart[0].equals("AddName") && !namePart[1].equals(name) && !serverListModel.contains(namePart[1])) {
serverListModel.addElement(namePart[1]);
}
if(namePart[0].equals("RemoveName") && !namePart[1].equals(name)) {
serverListModel.removeElement(namePart[1]);
}
if(!msg.equals(null) && !namePart[0].equals("AddName") && !namePart[0].equals("RemoveName")) {
chatWindow.append(msg+"\n");
}
}
} catch (IOException | ClassNotFoundException e) {
chatWindow.append("Server Closed");
e.printStackTrace();
try {
s1.close();
} catch (IOException e1) {
e1.printStackTrace();
}
mainWindow(true);
}
}
}
public class ClientAudio implements Runnable { // CLIENT AUDIO
public void run() {
try {
o2 = new ObjectOutputStream(s2.getOutputStream());
System.out.println("AUDIO");
int bytesRead = 0;
byte[] soundData = new byte[1];
Thread car = new Thread(new ClientAudioRec());
car.start();
while(true) {
bytesRead = mic.read(soundData, 0, bytesRead);
if(bytesRead >= 0) {
o2.write(soundData, 0, bytesRead);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class ClientAudioRec implements Runnable { // CLIENT AUDIO REC
public void run() {
i2 = new ObjectInputStream(s2.getInputStream());
System.out.println("REC");
SourceDataLine inSpeaker = null;
DataLine.Info info = new DataLine.Info(SourceDataLine.class, af);
try {
inSpeaker = (SourceDataLine)AudioSystem.getLine(info);
inSpeaker.open(af);
} catch (LineUnavailableException e1) {
System.out.println("ERROR 22");
e1.printStackTrace();
}
int bytesRead = 0;
byte[] inSound = new byte[100];
inSpeaker.start();
while(bytesRead != -1)
{
try{
bytesRead = ((ObjectInput) i2).read(inSound, 0, inSound.length);
} catch (Exception e){
e.printStackTrace();
}
if(bytesRead >= 0)
{
inSpeaker.write(inSound, 0, bytesRead);
}
}
}
}

Java Socket Data received unordered

I am collecting data from Android App(Accelerometer and Gyro) and send it to Desktop app via Java Socket but in high rates
(SENSOR_DELAY_FASTEST,SENSOR_DELAY_GAME)
Notes :
readingsList : contains all reading from sensors
I remove from list the data being sent to server
Only data sent once and i made sure it's ordered from client side
but i got them unordered in server side ( I received all data but not ordered)
processData(String reading) function may takes time but not too much
Client Code :
class SocketClientThread implements Runnable {
public SocketClientThread(){
}
public void run() {
while (!Thread.currentThread().isInterrupted() && breathingStarted) {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
socket.setSendBufferSize(Integer.MAX_VALUE);
socket.setReceiveBufferSize(Integer.MAX_VALUE);
int lastCount = readingsList.size();
out.println(readingsList);
out.flush();
out.close();
int toberemoved = lastCount;
if(readingsList.size() > 0){
for (int i = 0; i < toberemoved; i++) {
readingsList.remove(0);
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
Server Code :
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(minutes*60*1000);
Thread thread = new Thread() {
public void run() {
while(!isStopped)
{
try
{
Socket connection = serverSocket.accept();
connection.setReceiveBufferSize(Integer.MAX_VALUE);
connection.setSendBufferSize(Integer.MAX_VALUE);
BufferedReader input =
new BufferedReader(new InputStreamReader(connection.getInputStream()));
PrintWriter out =
new PrintWriter(connection.getOutputStream(), true);
String inputLine;
while ((inputLine = input.readLine()) != null) {
recentReading = inputLine;
String oldReading = recentReading;
String modifiedReading = oldReading.replace("[", "");
modifiedReading = modifiedReading.replace("]", "");
String [] readings = modifiedReading.split(",");
for (int i = 0; i < readings.length; i++) {
String currentReading = readings[i].trim();
String [] tokens = currentReading.split("_");
processData(currentReading);
}
}
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
display.syncExec(new Runnable() {
public void run() {
statusVal.setText("Socket timed out!");
}
});
break;
}catch(SocketException s)
{
if(serverSocket.isClosed()){
display.syncExec(new Runnable() {
public void run() {
statusVal.setText("Disconnected");
}
});
}
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
};
thread.setDaemon(true);
thread.start();
I am getting data after it's time (not ordered)

Sending an image through socket as byte array in Java

I know this has been asked in a few different ways, but I've been working on this for 2 days with no avail. My code is failing in that the receiving side throws EOF exceptions constantly. Can someone point me in the right direction?
Receiving side:
class ReceiveThread extends Thread {
ReceiveThread() {
}
#Override
public void run() {
System.out.println("Receive Thread Start");
DataInputStream in;
try {
} catch (Exception e) {
return;
}
try {
in = new DataInputStream(connection.getInputStream());
while (true) {
if (!connection.isConnected()) {
System.out.println("Connection not connected");
break;
}
try {
int len = in.readInt();
byte[] data = new byte[len];
System.out.println("Image size: " + len);
if (len > 0) {
in.readFully(data, 0, len);
BufferedImage bi = ImageIO.read(new ByteArrayInputStream(data));
panel.updateImage(bi);
panel.repaint();
}
in.close();
} catch (Exception e) {
}
pause(100);
}
} catch (Exception e) {
}
}
public void pause(long time) {
try {
Thread.sleep(time);
} catch (Exception e) {
}
}
}
Sending side:
class UpdateScreenThread extends Thread {
Robot robot;
public UpdateScreenThread() {
try {
robot = new Robot();
System.out.println("Update Thread Created");
} catch (Exception e) {
}
}
#Override
public void run() {
System.out.println("Update Thread Running");
Settings.isSharing = true;
Dimension screenSize;
screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Rectangle screenRectangle = new Rectangle(screenSize);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream out;
try {
out = new DataOutputStream(s.getOutputStream());
} catch (Exception e) {
return;
}
while (s.isConnected()) {
//System.out.println("test");
BufferedImage bi = robot.createScreenCapture(screenRectangle);
try {
ImageIO.write(bi, "PNG", baos);
baos.flush();
byte[] bytes = baos.toByteArray();
out.flush();
out.writeInt(bytes.length);
out.flush();
out.write(bytes);
System.out.println("Image sent");
} catch (Exception e) {
}
pause(500);
}
try {
out.close();
} catch (Exception e) {
}
Settings.isSharing = false;
}
}
Thanks to anyone who can help. This is driving me INSANE.
Reduced to the essentials, this is your read loop:
public void run() {
//...
try {
in = new DataInputStream(connection.getInputStream());
while (true) {
//...
try {
int len = in.readInt();
byte[] data = new byte[len];
in.readFully(data, 0, len);
//...
in.close();
} catch (Exception e) {
}
pause(100);
}
} catch (Exception e) {
}
}
Note that the while (true) {...} includes in.close(). Move the close out of the loop.

Categories