TCP传输,客户端建立过程: 1、创建TCP客户端SOCKET服务,使用的Socket对象,并明确目的地要连接的主机; Socket socket = new Socket("192.168.1.4",10002); 2、如果连接建立成功,说明数据传输通道已建立。该通道就是Scoket流,是底层建立好的;可以用Socket对象来获取输出输入了流; OutputStream out = socket.getOutputStream(); 3、使用输出流将数据写出。 out.write("tcp演示".getBytes()); 4、关闭资源。 socket.close();
tcp服务端: 1、创建tcp服务端Socket服务,使用ServerSocket对象,指定一个端口供其他主机访问; ServerSocket ss = new ServerSocket(10002); 2、服务端为了不乱,会获取各个客户端Socket服务对象,用其自身的socket对象与其交流; Socket s = ss.accept(); String ip =s.getInetAddress().getHostAddress(); 3、通过客户端对象获取socket流读取客户端发来的数据 InputStream in = s.getInputStream(); byte[]buf = new byte[1024]; int len =in.read(buf); String text = new String(buf,o,len); 4、关闭资源。关客户端,关服务端;(关闭客户端是为了不占用服务端资源,而且在服务端关闭可控)
s.close(); //服务端一般不关闭;
import java.io.*; import java.net.*; public class Client{ public static void main(String[]args)throws IOException{ BufferedReader bufr = new BufferedReader(new FileReader("e:\\client.txt")); Socket ss = new Socket("192.168.1.4",9987); BufferedWriter bufout = new BufferedWriter(new OutputStreamWriter(ss.getOutputStream())); String line = null; while((line = bufr.readLine())!=null){ bufout.write(line); bufout.newLine(); bufout.flush(); } ss.shutdownOutput(); BufferedReader bufin = new BufferedReader(new InputStreamReader(ss.getInputStream())); String text = bufin.readLine(); System.out.println(text); bufr.close(); bufout.close(); bufin.close(); } }
import java.io.*; import java.net.*; public class Server{ public static void main(String[]args)throws IOException{ ServerSocket ss = new ServerSocket(9987); Socket s = ss.accept(); BufferedReader bufin = new BufferedReader(new InputStreamReader(s.getInputStream())); PrintWriter pw = new PrintWriter(new FileWriter("f:\\server.txt"),true); String line =null; while((line=bufin.readLine())!=null){ pw.println(line); } BufferedWriter bufout = new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); bufout.write("上传成功"); bufout.flush(); s.close(); pw.close(); } }
时间: 2024-10-08 00:56:26