TCP 通信编程
TCP:是一种可靠的网络协议,再通信两端都建立一个Socket对象。
通信之前要保证连接已经建立。
通过Socket产生IO流进行通信。
创建对象时,会连接服务器,连接不上,会报错。
所以,先运行服务端,再运行发送端。
具体过程,注释写的很清楚了。
发送数据
package demo1;import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;public class Client {public static void main(String[] args) throws IOException {// 创建连接通道Socket socket = new Socket("127.0.0.1", 1000);// 通过通道获取输出流OutputStream os = socket.getOutputStream();// 输出内容os.write("你好阿".getBytes());// 释放资源os.close();}
}
接收数据
package demo1;import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;public class Server {public static void main(String[] args) throws IOException {// 创建对象接收ServerSocket ss = new ServerSocket(1000);// 获取连接的通道Socket socket = ss.accept();// 根据通道获得输入流InputStream is = socket.getInputStream();// 字节流 转换为 字符流,再包装成缓冲字符流,不出现乱码,并 提高效率BufferedReader br = new BufferedReader(new InputStreamReader(is));// 读入String line;while ((line = br.readLine()) != null) {System.out.print(line);}// 释放资源socket.close();ss.close();}
}
传输文件 并 回馈
Client:
package demo3;import java.io.*;
import java.net.Socket;public class Client {public static void main(String[] args) throws IOException {// 建立连接Socket socket = new Socket("127.0.0.1", 1000);// 创建缓冲输入字节流BufferedInputStream bis = new BufferedInputStream(new FileInputStream("start/img.jpg"));// 创建输出流BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());// 读入文件并传输byte[] bytes = new byte[4096];int len;while ((len = bis.read(bytes)) != -1) {bos.write(bytes, 0, len);}// 写出结束标记socket.shutdownOutput();// 获取服务器回馈,读入,字节流转字符流,在转缓冲流BufferedReader br= new BufferedReader(new InputStreamReader(socket.getInputStream()));String line;line = br.readLine();System.out.println(line);// 释放资源socket.close();}
}
Server:
package demo3;import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;public class Server {public static void main(String[] args) throws IOException {// 创建对象ServerSocket ss = new ServerSocket(1000);// 接收连接Socket socket = ss.accept();// 读取数据,并保存到本地BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("target/b.jpg"));byte[] bytes = new byte[4096];int len;while ((len = bis.read(bytes)) != -1) {bos.write(bytes, 0, len);}// 写回数据BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));bw.write("上传成功");bw.flush();// 释放资源socket.close();ss.close();}
}
运行结果:回馈和传输成功