Java的Socket编程例子


//上传图片客户端代码
public class UploadImgClientDemo {

public static void main(String[] args) throws UnknownHostException, IOException {
                //创建socket对象
Socket socket=new Socket("192.168.1.104",12345);

BufferedInputStream bis=new BufferedInputStream

                (new FileInputStream("H:\\Copy\\M\\facebook\\Zack3\\smalls.jpg"));

BufferedOutputStream bos=new BufferedOutputStream(socket.getOutputStream());

byte[] bys=new byte[1024];
int len=0;
while((len=bis.read(bys))!=-1){
bos.write(bys, 0, len);
}
bos.flush();
socket.shutdownOutput();
InputStream in=socket.getInputStream();
len=in.read(bys);
String s=new String(bys,0,len);
System.out.println(s);

bis.close();
socket.close();

}

}


//多线程接收图片服务器端代码
public class UploadImgServerDemo {

public static void main(String[] args) throws IOException {
ServerSocket server=new ServerSocket(12345);

while(true){
Socket s=server.accept();
new Thread(new SocketThread(s)).start();
}
}

}

//多线程对象

public class SocketThread implements Runnable {
public static int i;
private Socket s;
public SocketThread(Socket s){
this.s=s;
}
@Override
public void run() {
BufferedOutputStream bos=null;
try {
BufferedInputStream bis=new BufferedInputStream(s.getInputStream());
String name=getName();
bos=new BufferedOutputStream(new FileOutputStream(name));
byte[] bys=new byte[1024];
int len=0;
while((len=bis.read(bys))!=-1){
bos.write(bys, 0, len);
}
bos.flush();
OutputStream out=s.getOutputStream();
bys="图片上传成功!".getBytes();
out.write(bys, 0, bys.length);

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{

try {
bos.close();
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private synchronized static String getName() {
i++;
return i+"small.jpg";
}
}

你可能感兴趣的:(java)