java socket
2022/5/2 1:12:41
本文主要是介绍java socket,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1.客户端传输到服务端
public void service() { ServerSocket serverSocket = null; InputStreamReader inputStreamReader = null; try { serverSocket = new ServerSocket(8899); Socket accept = serverSocket.accept(); InputStream inputStream = accept.getInputStream(); inputStreamReader = new InputStreamReader(inputStream); char[] cbuf = new char[5]; int len = 0; while ( (len = inputStreamReader.read(cbuf))!=-1 ){ System.out.print(new String(cbuf, 0, len)); } } catch (IOException e) { e.printStackTrace(); } finally { if (inputStreamReader != null) { try { inputStreamReader.close(); } catch (IOException e) { e.printStackTrace(); } } if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } } @Test public void client() { Socket socket = null; OutputStreamWriter outputStreamWriter = null; try { InetAddress localHost = InetAddress.getLocalHost(); socket = new Socket(localHost,8899); OutputStream outputStream = socket.getOutputStream(); outputStreamWriter = new OutputStreamWriter(outputStream); outputStreamWriter.write("你好,我是客户端"); } catch (IOException e) { e.printStackTrace(); } finally { if (outputStreamWriter != null) { try { outputStreamWriter.close(); } catch (IOException e) { e.printStackTrace(); } } if (socket != null) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
这篇关于java socket的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23Springboot应用的多环境打包入门
- 2024-11-23Springboot应用的生产发布入门教程
- 2024-11-23Python编程入门指南
- 2024-11-23Java创业入门:从零开始的编程之旅
- 2024-11-23Java创业入门:新手必读的Java编程与创业指南
- 2024-11-23Java对接阿里云智能语音服务入门详解
- 2024-11-23Java对接阿里云智能语音服务入门教程
- 2024-11-23JAVA对接阿里云智能语音服务入门教程
- 2024-11-23Java副业入门:初学者的简单教程
- 2024-11-23JAVA副业入门:初学者的实战指南