服务端:
public class t10_5_s extends JFrame {
private ServerSocket server;
private Socket sock;
private DataInputStream dis;
private DataOutputStream dos;
private FileInputStream fis;
private PrintWriter pw;
public t10_5_s()
{
try {
server=new ServerSocket(8888);
sock=server.accept() ;
dos=new DataOutputStream (sock.getOutputStream() );
dos.writeUTF( "ok!");
dis=new DataInputStream (sock.getInputStream() );
pw=new PrintWriter (new FileWriter("d1.txt"));
String str=null;
while(true){
str=dis.readUTF();
System.out.println(str);
pw.print(str);
}
} catch (IOException e1) {
e1.printStackTrace();
}finally{
pw.close();
try {
sock.close();
server.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new t10_5_s();
}
}
java.io.EOFException
at java.io.DataInputStream.readUnsignedShort(DataInputStream.java:323)
at java.io.DataInputStream.readUTF(DataInputStream.java:572)
at java.io.DataInputStream.readUTF(DataInputStream.java:547)
at t10_5_s.<init>(t10_5_s.java:44)
at t10_5_s.main(t10_5_s.java:65)
客户端:
public class t10_5_c extends JFrame{
private Socket sock;
private DataInputStream dis;
private DataOutputStream dos;
private FileOutputStream fos;
private FileInputStream fis;
public t10_5_c()
{
try {
sock=new Socket("127.0.0.1",8888);
dis=new DataInputStream (sock.getInputStream() );
System.out.println(dis.readUTF());
fis=new FileInputStream("data.txt");
dos=new DataOutputStream(sock.getOutputStream());
int sum=fis.available();
int i=0;
while(i<sum){
if((sum-i) >100){
byte s[]=new byte[100];
fis.read(s,0,100);
String str=new String(s);
System.out.println(str);
dos.writeUTF( str);
}
else
{
byte s1[]=new byte[sum-i];
fis.read(s1,0,(sum-i));
String str=new String(s1);
System.out.println(str);
dos.writeUTF( str);
}
i+=100;
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{try {
sock.close();
} catch (IOException e1) {
// TODO 自动生成 catch 块
e1.printStackTrace();
}}
}
public static void main(String[] args) {
new t10_5_c();
}
}
红色部分是错误!想了好久没搞不懂!