当前位置:
首页 >
TCP协议下 Socket 与 ServerSocket
发布时间:2023/12/10
56
豆豆
生活随笔
收集整理的这篇文章主要介绍了
TCP协议下 Socket 与 ServerSocket
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
不多bb.
package c_20_1_5;import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException;public class TestSocket {public static void main(String[] args) {// Socket 与 ServerSocket// TCP 协议下的有连接, 安全传输协议。可用于任何大型文件的传输, 缺点是速度慢。//server();client();}public static void client() { Socket s = null;FileInputStream fis = null;try {System.out.println("客户端开启, 正在访问服务器...");// 发送到的地方s = new Socket(InetAddress.getByName("127.0.0.1"), 10086);// 网络输出流OutputStream out = s.getOutputStream();fis = new FileInputStream("晴天-周杰伦.mp3");byte[] b = new byte[1024*8];System.out.println("正在发送...");int len;while ((len = fis.read(b)) != -1) {// 分段发送到10086out.write(b, 0, len);}System.out.println("发送完成。");} catch (UnknownHostException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (fis != null)fis.close();s.close();} catch (IOException e) {e.printStackTrace();}}}public static void server() {ServerSocket ss = null;Socket s = null;FileOutputStream fis = null;// 以10086作为服务端try {System.out.println("服务端开启...");ss = new ServerSocket(10086);System.out.println("等待客户端连接...");s = ss.accept();InputStream in = s.getInputStream();fis = new FileOutputStream("晴天2.mp3");byte[] b = new byte[1024*8]; int len;while ((len = in.read(b)) != -1) {fis.write(b, 0, len);}System.out.println("上传成功。");} catch (IOException e) {e.printStackTrace();}} }
总结
以上是生活随笔为你收集整理的TCP协议下 Socket 与 ServerSocket的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: mvc框架异常处理机制
- 下一篇: oracle11g 隐藏参数_ORACL