[PROBLEMA] Codice Java Clicca QUI per vedere il messaggio nel forum |
Verce |
Ciao a tutti, ho un problema con questo pezo di codice...
In pratica x esercitarmi volevo creare un sistema che leggeva i dati da un client e glieli rispediva (una specie di base per una chat) ma ho un problema che non riesco a risolvere, in pratica il server dopo aver letto ciò che gli manda il client (i System.out sono per il debug) si blocca (e non so perchè) dentro il while della 'public static void In' se si fa girare il programa la cosa si nota in quanto non stampa la frase ("ora ritorno: " + r)
Non so che errore ho fatto.. qualcuno sa aiutarmi?
Posto quà sotto il codice..
import java.net.*;
import java.io.*;
class Ser extends Thread{
public static void main(String args[]) throws Exception {
ServerSocket s=(ServerSocket)null;
String frase;
try {
s = new ServerSocket(4500,300);
} catch (IOException e) { }
while (true) {
try {
Socket User;
User=s.accept();
System.out.println("son connesso!");
frase=In(User);
System.out.println(frase);
Out(User,frase);
} catch (IOException e) { }
}
}
public static void Out(Socket s,String r) throws Exception {
int slength;
OutputStream sOut;
sOut=s.getOutputStream();
slength = r.length();
for (int i=0; i<slength; i++) {
sOut.write((int)r.charAt(i));
}
}
public static String In(Socket s) throws Exception{
int c;
String r="";
InputStream sIn=s.getInputStream();
while ((c = sIn.read()) != 13) {
r = r + (char)c;
System.out.println("Server: " + r);
}
System.out.println("ora ritorno: " + r);
return r;
}
}
-----------------------------------------------------------------------------
import java.net.*;
import java.io.*;
class Cli extends Thread {
public static void main(String args[]) throws Exception {
Socket s;
int c;
String frase="";
s = new Socket("localhost",4500);
while (!frase.equals("exit")) {
while ((c=System.in.read()) != 13) {
frase=frase + (char)c;
}
Out(s,frase);
System.out.println("ho mandato: " + frase);
System.out.println(In(s));
}
s.close();
}
public static void Out(Socket s,String r) throws Exception {
int slength;
OutputStream sOut;
sOut=s.getOutputStream();
slength = r.length();
for (int i=0; i<slength; i++) {
sOut.write((int)r.charAt(i));
}
System.out.println("ho scritto: " + r);
}
public static String In(Socket s) throws Exception {
int c;
String r="";
InputStream sIn=s.getInputStream();
while ((c = sIn.read()) != -1) {
r = r + (char)c;
}
return r;
}
} |
yeah |
Per favore, usa i tag {code}{/code} (con parentesi quadre), l'assenza di indentazione mi confonde :D
Ora ci dò una occhiata...
[edit]
(Non testato)
Cambia
code: while ((c = sIn.read()) != 13) {
in
code: while ((c = sIn.read()) != 10) {
:)
|
0m4r |
oppure, invece di 10 o 13, usa
- '\r' che sta per carride return
- '\n' che sta per new line
che poi è lo stesso, ma a me sembra più "intuitivo"... |
Verce |
Ok, cambiando 13 con 10 ho risolto il problema!
Beh ora si blocca il passo dopo.. ma dovrei riuscire a risolvermelo da solo :cool: |
|
|
|