i tried to make a simple client-server (with some gui) the server sends the data and the client receive it (the save of the file works too) but the client seems to be stucked in the receive-loop.
I started both threads with ".start()".
I have marked the position of the problem with bold style.
My some of you have a idea why the programm in the client dont goes on... - best wishes ghali
Server:
public class Server extends Thread implements Runnable{
public File choosenfile;
public int port = 42001;
public boolean running = true;
public String myAdress = "localhost";
public ServerSocket serverSocket;
public BufferedInputStream bis;
public boolean debug = true;
public OutputStream os;
public void run() {
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(running){
Socket socket = null;
try {
System.out.println("Listening on port: "+port);
socket = serverSocket.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* Dies ist die stelle an der man einen Thread aufmachen kann
*/
// 1. File-Hülle anlegen dazu muss man deren größere wissen
if(debug) System.out.println("Server: 1.");
int count;
byte[] buffer = new byte[1024];
try {
os = socket.getOutputStream();
} catch (IOException e1) {
e1.printStackTrace();
}
BufferedInputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(choosenfile));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
try {
while ((count = in.read(buffer)) > 0) {
os.write(buffer, 0, count);
os.flush();
}
} catch (IOException e1) {
e1.printStackTrace();
}
if(debug) System.out.println("Server: finish sending");
try {
os.flush();
if(debug) System.out.println("Server: close");
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
running =false;
}
}
}
Client:
public class Client extends Thread implements Runnable{
public Gui gui; //graphical surface
public boolean running = true;
public boolean debug =true;
//Networkstuff
Socket socket;
DataInputStream is;
public byte[] returnFile;
public Client(Gui gui){
this.gui = gui;
}
public void run() {
try {
socket = new Socket(InetAddress.getByName(gui.inetAdress),gui.portServer);
} catch (UnknownHostException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(gui.path);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedOutputStream out = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024];
int count;
InputStream in = null;
try {
in = socket.getInputStream();
int i =0;
}
catch (IOException e1) {
e1.printStackTrace();
}
try {
while((count=in.read(buffer)) >0){
fos.write(buffer, 0, count);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
**//folloing functions are not executed anymore and i dont know why**
gui.loadPicture();
try {
fos.close();
socket.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
It's quite simple. read() blocks until
data is available in the stream, or
the stream is closed
The server sends bytes to the stream, but never closes it, so the client reading from this stream doesn't have any way to know if some more data will come or not, so it blocks.
Close the stream at server-side, or design a protocol allowing the client to know when to stop reading (like for example sending the number of bytes in the file, then sending these bytes).
Related
i can't figure out why my client socket keeps falling in an IOException.
When it falls in the IOException i recreate my socket and so it will work again untill it falls again into the Exception and so on ...
the code should always read out an ip controller from my electrical installation. I cant change anything on the server side. I connect to it and when something happens it post it to the port and i want to be able to read it.
this is the opening socket code
public KnxController(){
try{
System.out.println("Server started");
clientSocket = new Socket(IP, PORT);
outToServer = new DataOutputStream(clientSocket.getOutputStream());
} catch (UnknownHostException e) {
System.out.println("UnknownHostException: kan knx niet vinden");
} catch (IOException e) {
System.out.println("IOException knxcontroller: kan geen data sturen");
}
and here i read out the data
while(true){
try {
DataInputStream din=new DataInputStream(knxC.clientSocket.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(din));
String[] str=br.readLine().split("");
System.out.println(Arrays.toString(str));
} catch (IOException e) {
try {
knxC.clientSocket = new Socket(knxC.IP, knxC.PORT);
} catch (UnknownHostException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch(NullPointerException nex){
try {
knxC.clientSocket = new Socket(knxC.IP, knxC.PORT);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
it workes but far from good coding.
any help on how to solve this would be appreciated.
cleaned the above code for anyone who's interested
opening a socket
public KnxController(){
do{
setClientSocket();
try {
outToServer = new DataOutputStream(clientSocket.getOutputStream());
} catch (IOException e) {
log.error("IOException knxcontroller: kan geen data out stream starten naar knx");
} catch (NullPointerException nEx){
log.error("NullPointerException knxcontroller: geen knx host");
}
}while(clientSocket == null);
KnxSocketListener knxL = new KnxSocketListener("KnxSocketListener", this);
knxL.start();
}
public void setClientSocket() {
try {
this.clientSocket = new Socket(IP, PORT);
} catch (UnknownHostException e) {
log.error("UnknownHostException: kan geen socket opbouwen met knx host");
} catch (IOException e) {
log.error("IOException: kan geen socket opbouwen met knx host");
}
}
socketlistener in new thread public class KnxSocketListener
public KnxSocketListener(String name, KnxController knxC) {
threadName = name;
System.out.println("Creating " + threadName );
this.knxC = knxC;
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
public void run()
{
while(true){
try {
DataInputStream din = new DataInputStream(knxC.getClientSocket().getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(din));
String[] str=br.readLine().split("");
System.out.println(Arrays.toString(str));
} catch (IOException e) {
knxC.setClientSocket();
} catch(NullPointerException nex){
knxC.setClientSocket();
}
}
}
I want to send object (custom class) via socket from Client to Server. This is my code:
Server:
private class SocketServerThread extends Thread {
#Override
public void run() {
try {
serverSocket = new ServerSocket(socketServerPORT);
while (true) {
clientSocket = serverSocket.accept();
ObjectInputStream inObject = new ObjectInputStream(
clientSocket.getInputStream());
try {
Te xxx = (Te) inObject.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
//DataInputStream dataInputStream = new DataInputStream(
//clientSocket.getInputStream());
//messageFromClient=dataInputStream.readUTF();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
//activity.msgFromC.setText(messageFromClient);
}
});
}
}
Client:
public Client(String aIPaddres, int aPort, Te u) {
AddressIP = aIPaddres;
Port = aPort;
sendUser = u;
}
protected Void doInBackground(Void... arg0) {
Socket clientSocket = null;
try {
clientSocket = new Socket(AddressIP, Port);
ObjectOutputStream outObject = new ObjectOutputStream(
clientSocket.getOutputStream());
outObject.writeObject(sendUser);
//DataOutputStream daneWyjsciowe = new DataOutputStream(
//clientSocket.getOutputStream());
//daneWyjsciowe.writeUTF("Czesc!" );
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//response = "IOException: " + e.toString();
} finally {
if (clientSocket != null) {
try {
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
Custom class (Te.class):
public class Te implements Serializable {
public String message;
public Te(String m){
message=m;
}
}
When I passing simple data i.e. String there is no problem. But now I want to pass object, but there is always ClassNotFoundException at server. I read lot of stacks but I didnt find answer. Could U help me?
I've made some java code which connects and sends data to my android device over LAN, at the receiver side, the app uses AudioTrack to play the audio.
It seems to be streaming the audio, but the receiver plays back only noise!
Here is my sender code:
MainActivity has the following function -
public void startStream() {
//initiate the audioTrack and play it, then start listening
try {
int minBufferSize = AudioTrack.getMinBufferSize(44100,AudioFormat.CHANNEL_OUT_STEREO,AudioFormat.ENCODING_PCM_16BIT);
audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,44100, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, minBufferSize, AudioTrack.MODE_STREAM);
audioTrack.play();
Streamer streamer = new Streamer(MainActivity.this);
streamer.execute();
}catch(Exception e) {
say("mainSuperException");
}
}
This is the Streamer class:
public class Streamer extends AsyncTask<Void, Void, Void> {
MainActivity mainActivity = null;
int i = 0;
Streamer(MainActivity m)
{
mainActivity = m;
}
protected Void doInBackground(Void... p) {
try {
byte[] buffer = new byte[1024];
ServerSocket serverSocket = new ServerSocket(3210);
Socket socket = serverSocket.accept();
DataInputStream input = new DataInputStream(socket.getInputStream());
i = 0;
byte[] size = new byte[4];
input.read(size,0,4);
int s = ByteBuffer.wrap(size).getInt();
//Start streaming the file
while (i<s) {
try {
input.read(buffer,0,1024);
++i;
mainActivity.audioTrack.write(buffer, 0, buffer.length);
Log.d("packetTag", "got "+i);
} catch (IOException e) {
e.printStackTrace();
mainActivity.say("InnerioException");
} catch (IllegalStateException e) {
Log.e("packetTag", e.toString());
mainActivity.say("InnerIllegalStateException");
} catch (Exception e) {
Log.e("InnerSuperException", e.toString());
e.printStackTrace();
mainActivity.say("InnerSuperException");
}
}
} catch (IOException io) {
Log.e("ioexception", io.toString());
mainActivity.say("OuterioException");
} catch (Exception e) {
Log.e("SuperException", e.toString());
e.printStackTrace();
mainActivity.say("OuterSuperException");
}
return null;
}
}
And for the sender I used the following Java code:
public class mainClassSend {
public static void main(String[] s)
{
try {
InputStream songInputStream = new FileInputStream("D:\\song.mp3");
byte[] buffer = new byte[1024];
InetAddress group = InetAddress.getByName("192.168.2.8");
Socket socket = new Socket(group,3210);
int i=0;
byte[] size = ByteBuffer.allocate(4).putInt(3359).array();
socket.getOutputStream().write(size);
//Start streaming the file
while ((songInputStream.read(buffer, 0, buffer.length)) > -1) {
try {
socket.getOutputStream().write(buffer, 0, buffer.length);
++i;
System.out.println(i);
} catch (IOException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
songInputStream.close();
socket.close();
System.out.println(i);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Right now I'm just desperately trying to get this to work, so I've filled in all the values explicitly, even figured out the exact number of frames it sends, and sent that as the size.
It receives the size correctly, and keeps looping till that value, but all I hear is static.
I've looked all over stackOverflow, and tried looking into a lot of java class documentations, can't seem to figure out whats wrong here.
What am I trying to do
Simulate a socialnetwork program,in which you can add your profile,change your status,your picture,add friends etc.The program must save it's content before closing in a file.
How do I intend to do it
As I can not append with ObjectOutputStream. I though of creating an ArrayList<SocialProfiles> (SocialProfiles) in this case are the profiles which I am trying to save.
I want to load the profiles from the file to the ArrayList when the program starts,and when I am done adding profiles, I want to write the profiles from the ArrayList back to the file.
I am using the size of the array as an index.Example when it first writes to the array,it writes to index 0.When it has 1 element it writes to index 1 etc etc.
What is not going as it is supposed to?
The program does not load the data from the file to the array.
What do I call at Main
try {
fileoutput = new FileOutputStream("database.dat");
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
output = new ObjectOutputStream(fileoutput);
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
try {
fileinput = new FileInputStream("database.dat");
} catch (FileNotFoundException e2) {
// TODO Auto-generated catch block
System.out.println("File database.dat nuk ekziston");
}
try {
input = new ObjectInputStream(fileinput);
} catch (IOException e2) {
}
loadData();
frame.addWindowListener(new WindowAdapter()
{
#Override
public void windowClosing(WindowEvent e)
{
new Thread()
{
#Override
public void run()
{
writeData();
try {
fileinput.close();
fileoutput.close();
input.close();
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.exit(0);
}
}.start();
}
});
Methods
public void loadData(){
try{
while (true)
{
SocialProfile temp;
temp = (SocialProfile)input.readObject();
profiles.add(profiles.size(),temp);
}
}
catch(NullPointerException e){
}
catch(EOFException e){
System.out.println("U arrit fund-i i file");
} catch (ClassNotFoundException e) {
System.out.println("Objekt-i i lexuar nuk u konvertua dot ne klasen e caktuar");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void writeData(){
SocialProfile temp;
for(int i=0;i<profiles.size();i++){
temp=profiles.get(i);
try {
output.writeObject(temp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Try to serialize/deserialize whole array instead of each object.
public void serializeData(String filename, ArrayList<SocialProfile>arrayList) {
FileOutputStream fos;
try {
fos = openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arrayList);
oos.flush();
oos.close();
} catch (FileNotFoundException e) {
...
}catch(IOException e){
...
}
}
private ArrayList<SocialProfile> deserializeData(String filename){
try{
FileInputStream fis = openFileInput(filename);
ObjectInputStream ois = new ObjectInputStream(fis);
return (ArrayList<SocialProfile>)ois.readObject();
} catch (FileNotFoundException e) {
...
}catch(IOException e){
...
}catch(ClassNotFoundException e){
...
}
}
I'm working on a really simple Java Client / Server system (Just to get my feet wet with sockets). For some reason, I keep getting a "Socket is closed" error... here is my code..
Server File
public class Server {
public static ServerSocket s = null;
public static void main(String[] args) {
//Create the server socket
int port = 1111;
if (args.length > 0) {
if (isInt(args[0]) && Integer.parseInt(args[0]) < 65537) {
port = Integer.parseInt(args[0]);
}
}
try {
s = new ServerSocket(port);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
s.setSoTimeout(0);
} catch (SocketException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Runnable r = new Runnable() {
public void run() {
while (true) {
Socket caught = null;
try {
caught = Server.s.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (caught == null) {
return;
}
InputStream is = null;
try {
is = caught.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
String output;
while ((output = br.readLine()) != null) {
handleCommand(output, caught);
}
} catch (Exception e) {
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Thread t = new Thread(r);
t.start();
}
public static boolean isInt(String in) {
try {
Integer.parseInt(in);
return true;
} catch (Exception e) {
return false;
}
}
public static void handleCommand(String in, Socket s1) {
if (in.equalsIgnoreCase("test")) {
System.out.println("Recieved Test Command..");
System.out.println("Sending response..");
PrintStream ps = null;
try {
ps = new PrintStream(s1.getOutputStream(), true);
} catch (Exception e) {
e.printStackTrace();
}
ps.close();
}
}
}
Client File
public class Client {
public static Socket s = null;
public static void main(String[] args) {
int port = 1111;
String server = "localhost";
if (args.length > 0) {
if (isInt(args[0]) && Integer.parseInt(args[0]) < 65537) {
port = Integer.parseInt(args[0]);
}
}
if (args.length > 1) {
server = args[1];
}
try {
s = new Socket(server, port);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (s != null) {
Runnable r = new Runnable() {
public void run() {
while (true) {
InputStream is = null;
try {
is = s.getInputStream();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (Exception e) {
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
};
Thread t = new Thread(r);
t.start();
PrintStream ps = null;
try {
ps = new PrintStream(s.getOutputStream(), true);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Sending Test message..");
try {
ps.println("test");
} catch (Exception e) {
System.out.println("Error: - " + e.getMessage());
}
}
}
public static boolean isInt(String in) {
try {
Integer.parseInt(in);
return true;
} catch (Exception e) {
return false;
}
}
}
I get the error in the client on line 41 and then a NullPointerException on line 46..
Thanks in advance for any help. I'm just trying to learn here.
in the server on line 61, when you do your first read, your client didn't had the oportunity to send data, so it don't stops in the loop and move forward to close the reader on line 68.
Try to create a class to handle incoming connections at the server, that makes easier to think about what to do in the server, something like ClientHandler would be a good choice ;)
have fun !