一、SOCKET原理1.1 SOCKET概念
1.2建立socket连接 建立socket连接至少需要一对socket,其中一个运行与客户端,称为clientSocket,另一个运行于服务器端,称为serverSocket.
二、socket中TCP的三次握手建立连接详解我们知道tcp建立连接要进行“三次握手”,即交换三个分组。那么socket这个三次握手发生在socket的哪几个函数呢?
三、socket中TCP的四次握手释放连接详解
四、 C#和JAVA的socket实践
C#实现的客户端: using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Drawing;using System.Net;using System.Net.Sockets;using System.IO;using System.Runtime.Serialization.Formatters.Binary;using System.Collections.Generic;using System.Threading; namespace ClientMany{ class Program { static void Main(string[] args) { Console.WriteLine('Client Running...'); //定义要传送的信息 string msg = '这个是客户端的消息'; string filename = 'C:\\send\\image.jpg'; string str1 = SentPictures(filename, msg); str1 = str1 + '#' + str1 + '#' + str1 + '#' + str1 + '#' + str1; Send(str1); //按Q退出 ConsoleKey key; Console.WriteLine('\n\n 输入 \'Q\'键退出。n继续'); do { key = Console.ReadKey(true).Key; } while (key != ConsoleKey.Q); } /// <summary> /// 向远程客户端发送图片 /// 这一步是base64编码 /// </summary> /// <param name='strRemoteIP'>远程客户端IP</param> /// <param name='sendPort'>发送图片的端口</param> private static string SentPictures(String filename,String str) { String str1; if (File.Exists(filename)) { FileInfo file = new FileInfo(filename); var stream = file.OpenRead(); byte[] buffer = new byte[file.Length]; //读取图片字节流 stream.Read(buffer, 0, Convert.ToInt32(file.Length)); //将base64字符串保存到base64.txt文件中 //将字节流转化成base64字符串 str1 = Convert.ToBase64String(buffer); } else { Console.WriteLine('文件不存在'); str1 = ''; } str1 = str + ')' + str1 ; return str1; } private static void Send(string str){ TcpClient client; try { client = new TcpClient(); client.Connect('localhost', 8500);//与服务器连接 } catch (Exception ex) { Console.WriteLine(ex.Message); return; } Console.WriteLine('发送消息'); NetworkStream streamToServer = client.GetStream(); byte[] buffer1 = Encoding.UTF8.GetBytes(str);//获得缓存同时规定编码为UTF-8 streamToServer.Write(buffer1, 0, buffer1.Length);//发往服务器 // Console.Read(); client.Close(); } }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 Java实现的服务器端: package com.wxshan.test;import lombok.extern.log4j.Log4j2;import net.coobird.thumbnailator.Thumbnails;import org.springframework.beans.BeanUtils;import org.springframework.messaging.simp.SimpMessagingTemplate;import java.io.*;import java.lang.reflect.InvocationTargetException;import java.net.ServerSocket;import java.net.Socket;import java.time.LocalDate;import java.time.LocalDateTime;import java.time.format.DateTimeFormatter;import java.util.*;@Log4j2public class ListenSocket extends Thread { //端口号 private static final int SERVER_PORT = 8500; //服务端socket private ServerSocket serverSocket = null; public ListenSocket() { try { if (null == serverSocket) { this.serverSocket = new ServerSocket(SERVER_PORT); } } catch (IOException e) { log.error(e.getMessage(), e); } } /** * 监听的线程 */ public void run() { Socket client; System.out.println('-------主监听线程----------start----------'); try { while (true) { client = serverSocket.accept(); Thread c_thread = new CreateServerThread(client); c_thread.start(); } } catch (IOException e) { log.error(e.getMessage(), e); } } class CreateServerThread extends Thread { private Socket client; private PrintWriter out = null; private BufferedReader in = null; InputStreamReader inSR; OutputStream outSR; CarWaringVO carWaringVO; public CreateServerThread(Socket client) throws IOException { System.out.println('启动分线程'); this.client = client; } public void run() { try { inSR = new InputStreamReader(client.getInputStream(), 'UTF-8');//规定编码 in = new BufferedReader(inSR);//接收请求的流 outSR = client.getOutputStream(); out = new PrintWriter(outSR); //String imgUrl = ''; HashMap<String, String> imgUrl = new HashMap<>(); int len = 0;//监听到的字符串长度 StringBuffer tStringBuffer = new StringBuffer();//监听到的字符串w char[] buf = new char[4096]; while ((len = in.read(buf)) != -1) { String string = new String(buf, 0, len); tStringBuffer.append(string); } //将接收的字符串分割出不同的消息 String[] stringInfo = tStringBuffer.toString().split('#'); for (int i = 0; i < stringInfo.length; i++) { UUID uuid = UUID.randomUUID(); String date = CommonUtils.dateParse(LocalDate.now(), 'yyyy/MM/dd'); String fileName = uuid + '.jpg'; String FilePath = new File(System.getProperty('java.io.tmpdir')).getParentFile().getParentFile().getAbsolutePath() + uploadPath + date + '/'; String urlpath = '/picture/car/' + date + '/' + fileName; String path = FilePath + fileName; File file = new File(FilePath); if (!file.exists()) { file.mkdirs(); } //imgUrl += urlpath + ','; //将消息的信息与照片分割出来 String[] strings = stringInfo[i].split('\\)'); //区别照片的类型 imgs(strings[0],imgUrl,urlpath); //对图片进行base64的反转码 base64ToFile(strings[1], path); System.out.println('客户端接收的消息:'+stringinfo + ',图片地址:'+urlpath); } catch (IOException e) { log.error(e.getMessage(), e); } finally { if (in != null) { try { in.close(); } catch (IOException e) { log.error(LogException.getTrace(e)); } } if (inSR != null) { try { inSR.close(); } catch (IOException e) { log.error(LogException.getTrace(e)); } } if (out != null) { try { out.close(); } catch (Exception e) { log.error(LogException.getTrace(e)); } } try { if (client != null) { client.close(); } } catch (IOException e) { log.error(LogException.getTrace(e)); } } } } /** * 将base64转化为文件 * 这步是base解码 * @param base64 * @param path * @return */ public boolean base64ToFile(String base64, String path) { byte[] buffer; InputStream stream; try { buffer = Base64.getDecoder().decode(base64); stream = new ByteArrayInputStream(buffer); Thumbnails.of(stream).scale(1f).outputQuality(0.5f).outputFormat('jpg').toFile(path); return true; } catch (Exception e) { throw new RuntimeException('base64字符串异常或地址异常\n' + e.getMessage()); } } /** * 关闭当前线程 */ public void closeSocketServer() { try { if (null != serverSocket && !serverSocket.isClosed()) { serverSocket.close(); } } catch (IOException e) { e.printStackTrace(); } }} |
|