网络编程TCP

 2023-09-06 阅读 19 评论 0

摘要:要想实现网络传输,需要考虑的问题有哪些? 1.1 如何才能准确的定位网络上的一台主机? 1.2 如何才能进行可靠的、高效的数据传输? 简单的说,你要知道数据的目的地(IP),你要用什么渠道传递数据(TCP/UDP); java如

要想实现网络传输,需要考虑的问题有哪些?

1.1 如何才能准确的定位网络上的一台主机?
1.2 如何才能进行可靠的、高效的数据传输?

简单的说,你要知道数据的目的地(IP),你要用什么渠道传递数据(TCP/UDP);

java如何实现的网络通信

使用IP地址---定位一台主机 使用端口号---定位一个应用

1).如何创建一个InetAddress的对象?getByName(""); 比如:InetAddress inet = InetAddress.getByName("192.168.10.165");
2).如何获取本机的一个InetAddress的对象?getLocalHost()
域名:getHostName() ip:getHostAddress()

对应有协议

对于传输层而言:分为TCP UDP (了解)

TCP的编程:  Socket ServerSocket
例子:
1.客户端发送内容给服务端,服务端将内容打印到控制台上。

2.客户端发送内容给服务端,服务端给予反馈。

3.从客户端发送文件给服务端,服务端保存到本地。并返回“发送成功”给客户端。并关闭相应的连接。
代码实现:客户端

public class TestTCP{@Testpublic void client () {Socket socket = null;OutputStream outputSteam  = null;FileINputStream fileInputStream  = null;try {socket = new Socket(InetAddress.getByName("127.0.0.1"),9999);fileInputStream  = new FileInputStream(new File("1.jpg"));byte[] b =new byte[1024];int len;outputSream  = socket.getOutputStream();while ((len = fileInputStream.read(b)) != -1){outputStream.write(b,0,len);}socket.shutdownOutput();//停止输出inputStream = socket.getInputStream();byte[] b1 = new byte[1024];int len1;while ((len1 =inputStream.read(b1) ) != -1){String str = new String(b,0,len1);System.out.println(str);}}catch(Exception e){e.printStackTrace();}finally{if (inputStream != null){try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}if (outputStream != null){try {outputStream.close();} catch (IOException e) {e.printStackTrace();}}if (fileInputStream != null){try {fileInputStream.close();} catch (IOException e) {e.printStackTrace();}}if (socket != null){try {socket.close();} catch (IOException e) {e.printStackTrace();}}}}
} 

代码实现:服务端

@Test
public void server(){ServerSocket socket = null;InputStream inputStream = null;OutputStream outputStream = null;FileOutputStream fileOutputStream = null;Socket s = null;try {socket = new ServerSocket(9991);s = socket.accept();fileOutputStream = new FileOutputStream(new File("2.jpg"));byte[] b = new byte[1024];int len;inputStream = s.getInputStream();while ((len = inputStream.read(b)) != -1){fileOutputStream.write(b,0,len);}outputStream = s.getOutputStream();outputStream.write("我已经收到你发的文件了".getBytes());} catch (IOException e) {e.printStackTrace();}finally {if (outputStream != null){try {outputStream.close();} catch (IOException e) {e.printStackTrace();}}if (inputStream != null){try {inputStream.close();} catch (IOException e) {e.printStackTrace();}}if (fileOutputStream != null){try {fileOutputStream.close();} catch (IOException e) {e.printStackTrace();}}if (s != null){try {s.close();} catch (IOException e) {e.printStackTrace();}}if (socket != null){try {socket.close();} catch (IOException e) {e.printStackTrace();}}}
}

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/2/10238.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息