Java基础——网络编程(三)
TCP 网络编程
-- tcp 分为客户端和服务端
-- 客户端对应的对象是 Socket
-- 服务端对应的对象是 ServerSocket
-- 如果客户端先启动,则出现 connection refused 异常 //refused 拒绝
客户端创建Socket 对象时,就可以连接服务器,连接成功后,即形成通路,进行数据交换
import java.net.*; import java.io.*; //TCP客户端 class TClient{ public static void main(String [] args) throws Exception { Socket socket=new Socket("127.0.0.1",9000); //取得 Socket 中的输出流 OutputStream out =socket.getOutputStream(); out.write("这是客户端向主机输出的数据".getBytes()); //取得服务端发回的数据 InputStream in=socket.getInputStream(); byte [] buff=new byte[1024]; int len =in.read(buff); String str=new String(buff,0,len); System.out.println("服务端返回的数是:"+str); out.close(); in.close(); socket.close(); } }
//TCP服务端 /* 1 创建ServerSocket ,指定要监听的端口 2 通过 ServerSocket 的 accept 方法 (它是阻塞模式的) 取得连接上来的客户端对象 3 与客户端连通后,就可以得到客户端对象,并使用客户端对象读取流来取得数据 4 如果有必要,释放资源 */ import java.io.*; import java.net.*; class TServer { public static void main(String [] args) throws Exception { ServerSocket serverSocket=new ServerSocket(9000); //指定监听的端口 Socket clientSocket=serverSocket.accept(); //通过客户端的Socket对象可以取得信息 String clientIp=clientSocket.getInetAddress().getHostAddress(); int clientPort=clientSocket.getPort(); System.out.println(clientIp+":"+clientPort +"连接成功"); InputStream in= clientSocket.getInputStream(); byte[] buff=new byte[1024]; int len=in.read(buff); //len 表示读了多少个字节 注意,这个read 是阻塞的 String msg=new String(buff,0,len); System.out.println(msg); //往回发送数据 OutputStream out=clientSocket.getOutputStream(); out.write("小样的客户端,你竞敢骂人?,我也能".getBytes()); */ out.close(); in.close(); serverSocket.close(); clientSocket.close(); } }
例子 从客户端向服务端发字母,变成大写后反回
/* 客户端: 1 建立服务 2 获取键盘录入 3 将数入的数据发给服务端 4 接收服务端返回的大写字母 5 关闭资源 备注: 使用带缓冲的字符流进行操作 */ import java.io.*; import java.net.*; class TransClient { public static void main(String [] args) throws Exception { Socket socket=new Socket("127.0.0.1",8000); //定义输入流,读取键盘数据 BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); //定义输出流对象(用于将键盘数据写入到输出流中) BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); //定义一个socket 读取流,读取服务器返回的大写字母 BufferedReader brResult=new BufferedReader(new InputStreamReader(socket.getInputStream())); String str=null; while((str=br.readLine())!=null){ //从键盘开始读取 bw.write(str); //向服务端输出 bw.newLine(); bw.flush(); //千万别忘了 System.out.println("服务端返回的数据是"+brResult.readLine()); //取出变大写后的字符串 } socket.close(); br.close(); bw.close(); brResult.close(); } }
//服务端 import java.net.*; import java.io.*; class TransServer { public static void main(String [] args) throws Exception { ServerSocket serverSocket=new ServerSocket(8000); Socket clientSocket=serverSocket.accept(); //读取socket流中的数据(从客户端发过来的小写字母) BufferedReader br=new BufferedReader(new InputStreamReader( clientSocket.getInputStream())); //创建输出流对象,往clientSocket 的流中写入转换后的大写字母 BufferedWriter bw=new BufferedWriter(new OutputStreamWriter( clientSocket.getOutputStream())); String str=null; while((str=br.readLine())!=null) //注意 readLine 的特性,它是要一直读取回车换行才返回 { bw.write(str.toUpperCase()); bw.newLine(); bw.flush(); //千万别忘了 } br.close(); bw.close(); clientSocket.close(); serverSocket.close(); } }
例子 上传文件
//客户端 import java.io.*; import java.net.*; class UPClient { public static void main(String [] args) throws Exception { Socket socket=new Socket("127.0.0.1",7000); BufferedReader br=new BufferedReader(new FileReader("C:\\作业\\名单.txt")); //用来读文件的输入流 BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); //用来把文件往服务端传 //往scoket中一行一行的写入数据 String content=null; while((content=br.readLine())!=null){ bw.write(content); bw.newLine(); bw.flush(); } socket.shutdownOutput(); //关闭客端的输出流同,当相于加入一个结束标记(-1),要不然服务端会不停的等 //取出服务端返回的信息 BufferedReader brResult=new BufferedReader(new InputStreamReader(socket.getInputStream())) ; System.out.println( brResult.readLine()); bw.close(); br.close(); socket.close(); } }
//服务端 import java.io.*; import java.net.*; class UPServer { public static void main(String [] args) throws Exception { ServerSocket serverSocket=new ServerSocket(7000); Socket clientSocket=serverSocket.accept(); System.out.println(clientSocket.getInetAddress().getHostAddress()+"已经连接..."); //打印一下客户端连上的的信息 //读取客户端发过的来的数据 BufferedReader br=new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); BufferedWriter bw=new BufferedWriter(new FileWriter("e:/xxx.exe")); String str=null; while((str=br.readLine())!=null){ //如果客户端不发结束标记,它就不会返回 bw.write(str); bw.newLine(); bw.flush(); } //再向发送端返回一条提示息 BufferedWriter bwResult=new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())); bwResult.write("文件上传成功"); bwResult.flush(); serverSocket.close(); clientSocket.close(); bwResult.close(); bw.close(); br.close(); }
例子 上传图片
客户端 import java.net.*; import java.io.*; class ImgClient { public static void main(String [] ars) throws Exception { Socket socket=new Socket("127.0.0.1",7000); FileInputStream fis=new FileInputStream("C:\\image\\0.jpg"); //文件输入流 OutputStream out=socket.getOutputStream(); byte [] buff =new byte[1024]; int len=0; while((len=fis.read(buff))!=-1){ //一边读数据,一边传数据 out.write(buff,0,len); //字节流,不用flush, 和 newLine() } socket.shutdownOutput(); //加一个结束标记,表示输入流结束 //取出服务端发过来的信息 BufferedReader brResult=new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println(brResult.readLine()); socket.close(); fis.close(); } }
服务端 import java.net.*; import java.io.*; class ImgServer { public static void main(String [] args) throws Exception { ServerSocket serverSocket=new ServerSocket(7000); Socket clientSocket=serverSocket.accept(); System.out.println(clientSocket.getInetAddress().getHostAddress()+" 已连接"); InputStream in=clientSocket.getInputStream(); //取数据用的流 FileOutputStream fos=new FileOutputStream("e:\\xxx.jpg"); byte [] buff=new byte[1024]; int len=0; while((len=in.read(buff))!=-1){ fos.write(buff,0,len); //不用flush 因为是字节流 } BufferedWriter br=new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())); br.write("图片上传成功"); br.flush(); //别忘了 serverSocket.close(); clientSocket.close(); br.close(); fos.close(); } }
例子 多线程并发上传图片
服务端 import java.net.*; class PICServer { public static void main(String [] args) throws Exception { ServerSocket serverSocket=new ServerSocket(9000); while(true) { Socket clientSocket=serverSocket.accept(); new Thread(new PICThread(clientSocket)).start(); } } }
import java.io.*; import java.net.*; class PICThread implements Runnable{ private Socket clientSocket; public PICThread(Socket socket) { clientSocket=socket; } public void run() { try{ String clientIp=clientSocket.getInetAddress().getHostAddress(); FileOutputStream fos=new FileOutputStream("e:\\"+clientIp); InputStream in =clientSocket.getInputStream(); //从套接字中取出数据 byte[] buff=new byte[1024]; int len=0; while((len=in.read(buff))!=-1) //把数据从流中读出,写入文件 { fos.write(buff,0,len); } BufferedWriter br=new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream())); br.write("图片上传成功"); br.flush(); clientSocket.close(); fos.close(); in.close(); } catch(Exception ex){ System.out.println("出错了"); } } }
客户端 import java.io.*; import java.net.*; class PICClient{ public static void main(String [] args) throws Exception { String fileName=args[0]; //String fileName="c:\\Image\\2.jpg"; //进行验证 File file=new File(fileName); if(!(file.exists()&&file.isFile())) //验证文件是不是存在 { System.out.println("输入的文件名错误或是个目录"); return; } if( !file.getName().endsWith(".jpg")){ System.out.println("文件类型不正确"); return ; } if( file.length() >1024*1024){ System.out.println("你想干啥,整这么大的文件上来? 不行"); return; } Socket socket=new Socket("127.0.0.1",9000); FileInputStream fis=new FileInputStream(fileName); //构建文件输入流 OutputStream out=socket.getOutputStream(); //输出流 byte [] buff=new byte[1024]; int len=0; while((len=fis.read(buff))!=-1) //一边读入,一边往文件中写出 { out.write(buff,0,len); } socket.shutdownOutput(); //取出服务端发过来的信息 BufferedReader brResult=new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println(brResult.readLine()); socket.close(); fis.close(); brResult.close(); out.close(); } }