TCP(发消息:简易代码实现)
生活随笔
收集整理的這篇文章主要介紹了
TCP(发消息:简易代码实现)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
文章目錄
- 客戶端
- 服務(wù)器
- review:查詢IP和端口
- 發(fā)送文件
客戶端
服務(wù)器
review:查詢IP和端口
package com.ayv.try01;import java.net.InetAddress; import java.net.UnknownHostException; //測試IP public class TestInetadderss {public static void main(String[] args) {//InetAddress intAddress1 = null;try {//查詢本機(jī)地址InetAddress intAddress1 = InetAddress.getByName("127.0.0.1");System.out.println(intAddress1);InetAddress intAddress3 = InetAddress.getByName("localhost");System.out.println(intAddress3);InetAddress intAddress4 = InetAddress.getLocalHost();System.out.println(intAddress4);//查詢網(wǎng)站IP地址InetAddress intAddress2 = InetAddress.getByName("www.baidu.com");System.out.println(intAddress2);} catch (UnknownHostException e) {e.printStackTrace();}} }發(fā)送文件
//服務(wù)端 package com.ayv.try02;import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.ServerSocket; import java.net.Socket;public class TcpServerDamo2 {public static void main(String[] args) throws Exception {//創(chuàng)建服務(wù)ServerSocket serverSocket = new ServerSocket(9000);//監(jiān)聽客戶端的鏈接Socket socket = serverSocket.accept(); /**阻斷式監(jiān)聽,會(huì)一直等待客戶端鏈接*///獲取輸入流InputStream is = socket.getInputStream();//文件輸入FileOutputStream fos = new FileOutputStream(new File("receive.jpg"));byte[] buffer = new byte[1024];int len;while((len=is.read(buffer))!=-1){fos.write(buffer,0,len);}fos.close();is.close();socket.close();serverSocket.close();}} //客戶端 package com.ayv.try02;import java.io.File; import java.io.FileInputStream; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException;public class TCPClientDamo2 {public static void main(String[] args) throws Exception {//創(chuàng)建一個(gè)Socket鏈接Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 9000);//創(chuàng)建一個(gè)輸出流OutputStream os = socket.getOutputStream();//讀取文件FileInputStream fis = new FileInputStream(new File("觀望.jpg"));//寫出文件byte[] buffer = new byte[1024];int len;while((len=fis.read(buffer))!=-1){os.write(buffer,0,len);}//關(guān)閉資源fis.close();os.close();socket.close();} }總結(jié)
以上是生活随笔為你收集整理的TCP(发消息:简易代码实现)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 使用DQL查询数据
- 下一篇: 水馒头的功效与作用、禁忌和食用方法