socket上传文件java|java中怎么用socket 一次传多个文件啊

|

A. 关于用java的SOCKET传输文件

点对点传输文件/*import java.io.*;import java.net.*;import java.util.*;*/private HttpURLConnection connection;//存储连接 private int downsize = -1;//下载文件大小,初始值为-1 private int downed = 0;//文加已下载大小,初始值为0 private RandomAccessFile savefile;//记录下载信息存储文件 private URL fileurl;//记录要下载文件的地址 private DataInputStream fileStream;//记录下载的数据流try{ /*开始创建下载的存储文件,并初始化值*/ File tempfileobject = new File("h:\\webwork-2.1.7.zip"); if(!tempfileobject.exists()){ /*文件不存在则建立*/ tempfileobject.createNewFile(); } savefile = new RandomAccessFile(tempfileobject,"rw"); /*建立连接*/ fileurl = new URL("https://webwork.dev.java.net/files/documents/693/9723/webwork-2.1.7.zip"); connection = (HttpURLConnection)fileurl.openConnection(); connection.setRequestProperty("Range","byte="+this.downed+"-"); this.downsize = connection.getContentLength(); //System.out.println(connection.getContentLength()); new Thread(this).start(); } catch(Exception e){ System.out.println(e.toString()); System.out.println("构建器错误"); System.exit(0); } public void run(){ /*开始下载文件,以下测试非断点续传,下载的文件存在问题*/ try{ System.out.println("begin!"); Date begintime = new Date(); begintime.setTime(new Date().getTime()); byte[] filebyte; int onecelen; //System.out.println(this.connection.getInputStream().getClass().getName()); this.fileStream = new DataInputStream( new BufferedInputStream( this.connection.getInputStream())); System.out.println("size = " + this.downsize); while(this.downsize != this.downed){ if(this.downsize – this.downed > 262144){//设置为最大256KB的缓存 filebyte = new byte[262144]; onecelen = 262144; } else{ filebyte = new byte[this.downsize – this.downed]; onecelen = this.downsize – this.downed; } onecelen = this.fileStream.read(filebyte,0,onecelen); this.savefile.write(filebyte,0,onecelen); this.downed += onecelen; System.out.println(this.downed); } this.savefile.close(); System.out.println("end!"); System.out.println(begintime.getTime()); System.out.println(new Date().getTime()); System.out.println(begintime.getTime() – new Date().getTime()); } catch(Exception e){ System.out.println(e.toString()); System.out.println("run()方法有问题!"); }}/***//FileClient.javaimport java.io.*;import java.net.*;public class FileClient {public static void main(String[] args) throws Exception {//使用本地文件系统接受网络数据并存为新文件File file = new File("d:\\fmd.doc");file.createNewFile();RandomAccessFile raf = new RandomAccessFile(file, "rw");// 通过Socket连接文件服务器Socket server = new Socket(InetAddress.getLocalHost(), 3318);//创建网络接受流接受服务器文件数据InputStream netIn = server.getInputStream();InputStream in = new DataInputStream(new BufferedInputStream(netIn));//创建缓冲区缓冲网络数据byte[] buf = new byte[2048];int num = in.read(buf);while (num != (-1)) {//是否读完所有数据raf.write(buf, 0, num);//将数据写往文件raf.skipBytes(num);//顺序写文件字节num = in.read(buf);//继续从网络中读取文件}in.close();raf.close();}}//FileServer.javaimport java.io.*;import java.util.*;import java.net.*;public class FileServer {public static void main(String[] args) throws Exception {//创建文件流用来读取文件中的数据File file = new File("d:\\系统特点.doc");FileInputStream fos = new FileInputStream(file);//创建网络服务器接受客户请求ServerSocket ss = new ServerSocket(8801);Socket client = ss.accept();//创建网络输出流并提供数据包装器OutputStream netOut = client.getOutputStream();OutputStream doc = new DataOutputStream(new BufferedOutputStream(netOut));//创建文件读取缓冲区byte[] buf = new byte[2048];int num = fos.read(buf);while (num != (-1)) {//是否读完文件doc.write(buf, 0, num);//把文件数据写出网络缓冲区doc.flush();//刷新缓冲区把数据写往客户端num = fos.read(buf);//继续从文件中读取数据}fos.close();doc.close();}}*/

B. JAVA socket传输二进制文件问题

可能LZ对使用浏览器进行用户名密码认证比较清楚SOCKET走的是TCP/IP协议,而浏览器方式走的是HTTP协议不管哪种方式,都是通过客户端程序上发到服务器端,而浏览器方式的通道都是默认OK的,而TCP方式则需要通过SOCKET来建立通道,传输的数据是通过报文格式,报文你可以理解是一串东东,这个东东可以是二进制,可以是十进制,可以是字符串对于进行用户名密码认证,你看成是字符串就行了根据客户端和服务端规定好的报文格式进行解析,验证的工作和HTTP协议的方式一样,简单来说就是放在servlet上进行。区别就是,SOCKET要自己建立连接以及自己制定报文格式,而浏览器方式只要通过request方式传送就OK了

C. 网上的Java基于Socket文件传输示例,一个客户端一个服务器端一个socket的Util辅助类怎么运行起来啊

服务器(Server) [java] view plain package com.socket.sample; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.net.ServerSocket; import java.net.Socket; public class ServerTest { int port = 8821; void start() { Socket s = null; try { ServerSocket ss = new ServerSocket(port); while (true) { // 选择进行传输的文件 String filePath = "D:\\lib.rar"; File fi = new File(filePath); System.out.println("文件长度:" + (int) fi.length()); // public Socket accept() throws // IOException侦听并接受到此套接字的连接。此方法在进行连接之前一直阻塞。 s = ss.accept(); System.out.println("建立socket链接"); DataInputStream dis = new DataInputStream( new BufferedInputStream(s.getInputStream())); dis.readByte(); DataInputStream fis = new DataInputStream( new BufferedInputStream(new FileInputStream(filePath))); DataOutputStream ps = new DataOutputStream(s.getOutputStream()); // 将文件名及长度传给客户端。这里要真正适用所有平台,例如中文名的处理,还需要加工,具体可以参见Think In Java // 4th里有现成的代码。 ps.writeUTF(fi.getName()); ps.flush(); ps.writeLong((long) fi.length()); ps.flush(); int bufferSize = 8192; byte[] buf = new byte[bufferSize]; while (true) { int read = 0; if (fis != null) { read = fis.read(buf); // 从包含的输入流中读取一定数量的字节,并将它们存储到缓冲区数组 b // 中。以整数形式返回实际读取的字节数。在输入数据可用、检测到文件末尾 (end of file) // 或抛出异常之前,此方法将一直阻塞。 } if (read == -1) { break; } ps.write(buf, 0, read); } ps.flush(); // 注意关闭socket链接哦,不然客户端会等待server的数据过来, // 直到socket超时,导致数据不完整。 fis.close(); s.close(); System.out.println("文件传输完成"); } } catch (Exception e) { e.printStackTrace(); } } public static void main(String arg[]) { new ServerTest().start(); } } 客户端工具(SocketTool) [java] view plain package com.socket.sample; import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.net.Socket; public class ClientSocket { private String ip; private int port; private Socket socket = null; DataOutputStream out = null; DataInputStream getMessageStream = null; public ClientSocket(String ip, int port) { this.ip = ip; this.port = port; } /** */ /** * 创建socket连接 * * @throws Exception * exception */ public void CreateConnection() throws Exception { try { socket = new Socket(ip, port); } catch (Exception e) { e.printStackTrace(); if (socket != null) socket.close(); throw e; } finally { } } public void sendMessage(String sendMessage) throws Exception { try { out = new DataOutputStream(socket.getOutputStream()); if (sendMessage.equals("Windows")) { out.writeByte(0x1); out.flush(); return; } if (sendMessage.equals("Unix")) { out.writeByte(0x2); out.flush(); return; } if (sendMessage.equals("Linux")) { out.writeByte(0x3); out.flush(); } else { out.writeUTF(sendMessage); out.flush(); } } catch (Exception e) { e.printStackTrace(); if (out != null) out.close(); throw e; } finally { } } public DataInputStream getMessageStream() throws Exception { try { getMessageStream = new DataInputStream(new BufferedInputStream( socket.getInputStream())); return getMessageStream; } catch (Exception e) { e.printStackTrace(); if (getMessageStream != null) getMessageStream.close(); throw e; } finally { } } public void shutDownConnection() { try { if (out != null) out.close(); if (getMessageStream != null) getMessageStream.close(); if (socket != null) socket.close(); } catch (Exception e) { } } } 客户端(Client) [java] view plain package com.socket.sample; import java.io.BufferedOutputStream; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.FileOutputStream; public class ClientTest { private ClientSocket cs = null; private String ip = "localhost";// 设置成服务器IP private int port = 8821; private String sendMessage = "Windows"; public ClientTest() { try { if (createConnection()) { sendMessage(); getMessage(); } } catch (Exception ex) { ex.printStackTrace(); } } private boolean createConnection() { cs = new ClientSocket(ip, port); try { cs.CreateConnection(); System.out.print("连接服务器成功!" + "\n"); return true; } catch (Exception e) { System.out.print("连接服务器失败!" + "\n"); return false; } } private void sendMessage() { if (cs == null) return; try { cs.sendMessage(sendMessage); } catch (Exception e) { System.out.print("发送消息失败!" + "\n"); } } private void getMessage() { if (cs == null) return; DataInputStream inputStream = null; try { inputStream = cs.getMessageStream(); } catch (Exception e) { System.out.print("接收消息缓存错误\n"); return; } try { // 本地保存路径,文件名会自动从服务器端继承而来。 String savePath = "E:\\"; int bufferSize = 8192; byte[] buf = new byte[bufferSize]; int passedlen = 0; long len = 0; savePath += inputStream.readUTF(); DataOutputStream fileOut = new DataOutputStream( new BufferedOutputStream(new FileOutputStream(savePath))); len = inputStream.readLong(); System.out.println("文件的长度为:" + len + "\n"); System.out.println("开始接收文件!" + "\n"); while (true) { int read = 0; if (inputStream != null) { read = inputStream.read(buf); } passedlen += read; if (read == -1) { break; } // 下面进度条本为图形界面的prograssBar做的,这里如果是打文件,可能会重复打印出一些相同的百分比 System.out.println("文件接收了" + (passedlen * 100 / len) + "%\n"); fileOut.write(buf, 0, read); } System.out.println("接收完成,文件存为" + savePath + "\n"); fileOut.close(); } catch (Exception e) { System.out.println("接收消息错误" + "\n"); return; } } public static void main(String arg[]) { new ClientTest().getMessage(); } } 测试是成功的,在DOS命令行下编译~~~

D. java socket传送文件怎么设置传送速度,比如一个文件100M,每次传送1024BYTE

你发送(和接受)的时候,每次发1024字节就可以啦

E. JAVA socket传送文件一直被阻塞

是不能等于来-1撒..他在等你那边源给他写东西呢..你应该在服务器端结束的时候给他写个东西过去..让他知道已经结束了..还有什么问题HI我哈 但是read方法本身不就有告知客户端文件传送结束的功能么 当读到文件结束符的时候它会返回-1的啊确实读文件结束就是-1…但是你的客户端读的不是文件啊..服务器才是读文件..所以服务器能正常结束..你的客户端读的服务器发来的东西..服务器读文件结束后就不给客户端发信息了..而客户端的read()方法是阻塞式方法..意思就是服务器不传给他数据他就会一直等..所以还是那样..在服务器端结束的时候给客户端发个消息说明已经结束了..客户端读到这个结束标志的时候也就不要再往文件里面写东西了..也结束..这样你的程序就正确了..

F. java中,利用socket传送大文件,中途停止问题

thread里面接收数据应该是一个循环把?那么就给这个循环加一个跳出条件,比如说版private boolean stop=true;在循环当中增加权 if(stop=false){ break;}public void setStop(boolean stop){ this.stop=stop;}然后在需要停的时候调用setStop(false)就可以了上面纯手打,代码拼写什么的可能有错大概就是这个意思顺便说一下,thread.interrupt()是用来防止sleep或者wait方法卡死的,不会让线程终结。你要让线程结束还是要手动让程序跳出循环

G. 在Android端使用socket传输图片到java服务器,求源代码

/***思想:1.直接将所有数据安装字节数组发送2.对象序列化方式*//***thread方式**@authorAdministrator*/{privatestaticfinalintFINISH=0;privateButtonsend=null;privateTextViewinfo=null;privateHandlermyHandler=newHandler(){@OverridepublicvoidhandleMessage(Messagemsg){switch(msg.what){caseFINISH:Stringresult=msg.obj.toString();//取出数据if("true".equals(result)){TestSocketActivity4.this.info.setText("操作成功!");}else{TestSocketActivity4.this.info.setText("操作失败!");}break;}}};@OverridepublicvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);super.setContentView(R.layout.activity_test_sokect_activity4);//StrictMode.setThreadPolicy(newStrictMode.ThreadPolicy.Builder()//.detectDiskReads().detectDiskWrites().detectNetwork()//.penaltyLog().build());//StrictMode.setVmPolicy(newStrictMode.VmPolicy.Builder()//.detectLeakedSqlLiteObjects().detectLeakedClosableObjects()//.penaltyLog().penaltyDeath().build());this.send=(Button)super.findViewById(R.id.send);this.info=(TextView)super.findViewById(R.id.info);this.send.setOnClickListener(newSendOnClickListener());}{@OverridepublicvoidonClick(Viewv){try{newThread(newRunnable(){@Overridepublicvoidrun(){try{//1:Socketclient=newSocket("192.168.1.165",9898);//2:ObjectOutputStreamoos=newObjectOutputStream(client.getOutputStream());//3:UploadFilemyFile=SendOnClickListener.this.getUploadFile();//4:oos.writeObject(myFile);//写文件对象//oos.writeObject(null);//避免EOFExceptionoos.close();BufferedReaderbuf=newBufferedReader(newInputStreamReader(client.getInputStream()));//读取返回的数据Stringstr=buf.readLine();//读取数据Messagemsg=TestSocketActivity4.this.myHandler.obtainMessage(FINISH,str);TestSocketActivity4.this.myHandler.sendMessage(msg);buf.close();client.close();}catch(Exceptione){Log.i("UploadFile",e.getMessage());}}}).start();}catch(Exceptione){e.printStackTrace();}}()throwsException{//包装了传送数据UploadFilemyFile=newUploadFile();myFile.setTitle("tangcco安卓之Socket的通信");//设置标题myFile.setMimeType("image/png");//图片的类型Filefile=newFile(Environment.getExternalStorageDirectory().toString()+File.separator+"Pictures"+File.separator+"b.png");InputStreaminput=null;try{input=newFileInputStream(file);//从文件中读取ByteArrayOutputStreambos=newByteArrayOutputStream();bytedata[]=newbyte[1024];intlen=0;while((len=input.read(data))!=-1){bos.write(data,0,len);}myFile.setContentData(bos.toByteArray());myFile.setContentLength(file.length());myFile.setExt("png");}catch(Exceptione){throwe;}finally{input.close();}returnmyFile;}}}{privateStringtitle;privatebyte[]contentData;privateStringmimeType;privatelongcontentLength;privateStringext;publicStringgetTitle(){returntitle;}publicvoidsetTitle(Stringtitle){this.title=title;}publicbyte[]getContentData(){returncontentData;}publicvoidsetContentData(byte[]contentData){this.contentData=contentData;}publicStringgetMimeType(){returnmimeType;}publicvoidsetMimeType(StringmimeType){this.mimeType=mimeType;}publiclonggetContentLength(){returncontentLength;}publicvoidsetContentLength(longcontentLength){this.contentLength=contentLength;}publicStringgetExt(){returnext;}publicvoidsetExt(Stringext){this.ext=ext;}}

下边是服务端

publicclassMain4{publicstaticvoidmain(String[]args)throwsException{ServerSocketserver=newServerSocket(9898);//服务器端端口System.out.println("服务启动……………………");booleanflag=true;//定义标记,可以一直死循环while(flag){//通过标记判断循环newThread(newServerThreadUtil(server.accept())).start();//启动线程}server.close();//关闭服务器}}{="D:"+File.separator+"myfile"+File.separator;//目录路径privateSocketclient=null;privateUploadFileupload=null;publicServerThreadUtil(Socketclient){this.client=client;System.out.println("新的客户端连接…");}@Overridepublicvoidrun(){try{ObjectInputStreamois=newObjectInputStream(client.getInputStream());//反序列化this.upload=(UploadFile)ois.readObject();//读取对象//UploadFile需要和客户端传递过来的包名类名相同,如果不同则会报异常System.out.println("文件标题:"+this.upload.getTitle());System.out.println("文件类型:"+this.upload.getMimeType());System.out.println("文件大小:"+this.upload.getContentLength());PrintStreamout=newPrintStream(this.client.getOutputStream());//BufferedWriterout.print(this.saveFile());//返回响应//BufferedWriterwriter=null;//writer.write("");}catch(Exceptione){e.printStackTrace();}finally{try{this.client.close();}catch(IOExceptione){e.printStackTrace();}}}privatebooleansaveFile()throwsException{//负责文件内容的保存/***java.util.UUID.randomUUID():*UUID.randomUUID().toString()是javaJDK提供的一个自动生成主键的方法。UUID(Universally*UniqueIdentifier)全局唯一标识符,是指在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的,*是由一个十六位的数字组成*,表现出来的形式。由以下几部分的组合:当前日期和时间(UUID的第一个部分与时间有关,如果你在生成一个UUID之后,*过几秒又生成一个UUID,*则第一个部分不同,其余相同),时钟序列,全局唯一的IEEE机器识别号(如果有网卡,从网卡获得,没有网卡以其他方式获得*),UUID的唯一缺陷在于生成的结果串会比较长,字符串长度为36。**UUID.randomUUID().toString()是javaJDK提供的一个自动生成主键的方法。UUID(Universally*UniqueIdentifier)全局唯一标识符,是指在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的,*是由一个十六位的数字组成,表现出来的形式*/Filefile=newFile(DIRPATH+UUID.randomUUID()+"."+this.upload.getExt());if(!file.getParentFile().exists()){file.getParentFile().mkdir();}OutputStreamoutput=null;try{output=newFileOutputStream(file);output.write(this.upload.getContentData());returntrue;}catch(Exceptione){throwe;}finally{output.close();}}}{privateStringtitle;privatebyte[]contentData;privateStringmimeType;privatelongcontentLength;privateStringext;publicStringgetTitle(){returntitle;}publicvoidsetTitle(Stringtitle){this.title=title;}publicbyte[]getContentData(){returncontentData;}publicvoidsetContentData(byte[]contentData){this.contentData=contentData;}publicStringgetMimeType(){returnmimeType;}publicvoidsetMimeType(StringmimeType){this.mimeType=mimeType;}publiclonggetContentLength(){returncontentLength;}publicvoidsetContentLength(longcontentLength){this.contentLength=contentLength;}publicStringgetExt(){returnext;}publicvoidsetExt(Stringext){this.ext=ext;}}

H. java中怎么用socket 一次传多个文件啊

客户端接收多个文件的时候他所获取到的任然是一个字节流序列,所以你要确保第版一个文件的权序列有多长,第二个有多长….然后在客户端截取这些序列进行保存操作,处理方法有很多种,我以前用过的一种方法是接收数据时前1024个字节放文件名,然后的8个字节放文件大小,接着就是文件的信息。客户端只需要按这种方式解析就行了。。。希望对你有用。。。。

I. 如何使用java socket来传输自定义的数据包

以下分四点进行描述:1,什么是Socket网络上的两个程序通过一个双向的通讯连接实现数据的交换,这个双向链路的一端称为一个Socket。Socket通常用来实现客户方和服务方的连接。Socket是TCP/IP协议的一个十分流行的编程界面,一个Socket由一个IP地址和一个端口号唯一确定。但是,Socket所支持的协议种类也不光TCP/IP一种,因此两者之间是没有必然联系的。在Java环境下,Socket编程主要是指基于TCP/IP协议的网络编程。2,Socket通讯的过程Server端Listen(监听)某个端口是否有连接请求,Client端向Server 端发出Connect(连接)请求,Server端向Client端发回Accept(接受)消息。一个连接就建立起来了。Server端和Client 端都可以通过Send,Write等方法与对方通信。对于一个功能齐全的Socket,都要包含以下基本结构,其工作过程包含以下四个基本的步骤:(1) 创建Socket;(2) 打开连接到Socket的输入/出流;(3) 按照一定的协议对Socket进行读/写操作;(4) 关闭Socket.(在实际应用中,并未使用到显示的close,虽然很多文章都推荐如此,不过在我的程序中,可能因为程序本身比较简单,要求不高,所以并未造成什么影响。)3,创建Socket创建Socketjava在包java.net中提供了两个类Socket和ServerSocket,分别用来表示双向连接的客户端和服务端。这是两个封装得非常好的类,使用很方便。其构造方法如下:Socket(InetAddress address, int port);Socket(InetAddress address, int port, boolean stream);Socket(String host, int prot);Socket(String host, int prot, boolean stream);Socket(SocketImpl impl)Socket(String host, int port, InetAddress localAddr, int localPort)Socket(InetAddress address, int port, InetAddress localAddr, int localPort)ServerSocket(int port);ServerSocket(int port, int backlog);ServerSocket(int port, int backlog, InetAddress bindAddr)其中address、host和port分别是双向连接中另一方的IP地址、主机名和端 口号,stream指明socket是流socket还是数据报socket,localPort表示本地主机的端口号,localAddr和 bindAddr是本地机器的地址(ServerSocket的主机地址),impl是socket的父类,既可以用来创建serverSocket又可 以用来创建Socket。count则表示服务端所能支持的最大连接数。例如:学习视频网 http://www.xxspw.comSocket client = new Socket("127.0.01.", 80);ServerSocket server = new ServerSocket(80);注意,在选择端口时,必须小心。每一个端口提供一种特定的服务,只有给出正确的端口,才 能获得相应的服务。0~1023的端口号为系统所保留,例如http服务的端口号为80,telnet服务的端口号为21,ftp服务的端口号为23, 所以我们在选择端口号时,最好选择一个大于1023的数以防止发生冲突。在创建socket时如果发生错误,将产生IOException,在程序中必须对之作出处理。所以在创建Socket或ServerSocket是必须捕获或抛出例外。4,简单的Client/Server程序1. 客户端程序import java.io.*;import java.net.*;public class TalkClient {public static void main(String args[]) {try{Socket socket=new Socket("127.0.0.1",4700);//向本机的4700端口发出客户请求BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));//由系统标准输入设备构造BufferedReader对象PrintWriter os=new PrintWriter(socket.getOutputStream());//由Socket对象得到输出流,并构造PrintWriter对象BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));//由Socket对象得到输入流,并构造相应的BufferedReader对象String readline;readline=sin.readLine(); //从系统标准输入读入一字符串while(!readline.equals("bye")){//若从标准输入读入的字符串为 "bye"则停止循环os.println(readline);//将从系统标准输入读入的字符串输出到Serveros.flush();//刷新输出流,使Server马上收到该字符串System.out.println("Client:"+readline);//在系统标准输出上打印读入的字符串System.out.println("Server:"+is.readLine());//从Server读入一字符串,并打印到标准输出上readline=sin.readLine(); //从系统标准输入读入一字符串} //继续循环os.close(); //关闭Socket输出流is.close(); //关闭Socket输入流socket.close(); //关闭Socket}catch(Exception e) {System.out.println("Error"+e); //出错,则打印出错信息}}}2. 服务器端程序import java.io.*;import java.net.*;import java.applet.Applet;public class TalkServer{public static void main(String args[]) {try{ServerSocket server=null;try{server=new ServerSocket(4700);//创建一个ServerSocket在端口4700监听客户请求}catch(Exception e) {System.out.println("can not listen to:"+e);//出错,打印出错信息}Socket socket=null;try{socket=server.accept();//使用accept()阻塞等待客户请求,有客户//请求到来则产生一个Socket对象,并继续执行}catch(Exception e) {System.out.println("Error."+e);//出错,打印出错信息}String line;BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));//由Socket对象得到输入流,并构造相应的BufferedReader对象PrintWriter os=newPrintWriter(socket.getOutputStream());//由Socket对象得到输出流,并构造PrintWriter对象BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));//由系统标准输入设备构造BufferedReader对象System.out.println("Client:"+is.readLine());//在标准输出上打印从客户端读入的字符串line=sin.readLine();//从标准输入读入一字符串while(!line.equals("bye")){//如果该字符串为 "bye",则停止循环os.println(line);//向客户端输出该字符串os.flush();//刷新输出流,使Client马上收到该字符串System.out.println("Server:"+line);//在系统标准输出上打印读入的字符串System.out.println("Client:"+is.readLine());//从Client读入一字符串,并打印到标准输出上line=sin.readLine();//从系统标准输入读入一字符串} //继续循环os.close(); //关闭Socket输出流is.close(); //关闭Socket输入流socket.close(); //关闭Socketserver.close(); //关闭ServerSocket}catch(Exception e){System.out.println("Error:"+e);//出错,打印出错信息}}}


赞 (0)