-
大小: 2KB文件類型: .zip金幣: 2下載: 0 次發(fā)布日期: 2021-05-13
- 語言: 其他
- 標(biāo)簽: 聊天室??數(shù)據(jù)傳輸??
資源簡(jiǎn)介
基于UDP的數(shù)據(jù)傳輸與基于TCP的簡(jiǎn)易聊天,通俗易懂,開啟網(wǎng)絡(luò)編程之路。

代碼片段和文件信息
package?com.example.pay;
import?java.io.*;
import?java.net.*;
/**
?*?@author?sunyiran
?*?@date?2018-10-19
?*/
public?class?Client?{
????static?class?UDPClient?{
????????DatagramSocket?socket;
????????UDPClient(int?port)?throws?SocketException?{
????????????this.socket?=?new?DatagramSocket(port);
????????}
????????public?void?receive()?throws?IOException?{
????????????while?(true)?{
????????????????//定義信息存儲(chǔ)結(jié)構(gòu)(最大為64kb)
????????????????DatagramPacket?packet?=?new?DatagramPacket(new?byte[1024]?1024);
????????????????//開始接受輸入流
????????????????this.socket.receive(packet);
????????????????//獲取信息
????????????????byte[]?data?=?packet.getData();
????????????????System.out.println(new?String(data));
????????????}
????????}
????}
????static?class?TCPClient?{
????????//指定發(fā)送端的端口
????????ServerSocket?socket;
????????TCPClient(int?port)?throws?IOException?{
????????????this.socket?=?new?ServerSocket(port);
????????}
????????/**
?????????*?建立通信
?????????*?@param?username?用戶名
?????????*?@throws?IOException
?????????*/
????????public?void?connect(String?username)?throws?IOException?{
????????????Socket?accept?=?socket.accept();
????????????OutputStream?out?=?accept.getOutputStream();
????????????InputStream?in?=?accept.getInputStream();
????????????BufferedReader?sin?=?new?BufferedReader(new?InputStreamReader(System.in));
????????????BufferedReader?reader?=?new?BufferedReader(new?InputStreamReader(in));
????????????PrintWriter?writer?=?new?PrintWriter(new?OutputStreamWriter(out));
????????????String?line;
????????????while?(!(line?=?sin.readLine()).equalsIgnoreCase(“再見“))?{
????????????????writer.println(username?+?“:?“?+?line);
????????????????writer.flush();
????????????????System.out.println(username?+?“:?“?+?line);
????????????????System.out.println(reader.readLine());
????????????}
????????????writer.close();
????????????reader.close();
????????????sin.close();
????????????this.socket.close();
????????}
????}
????public?static?void?main(String[]?args)?throws?IOException?{
//????????UDPClient?client?=?new?UDPClient(8081);
//????????client.receive();
????????TCPClient?client1?=?new?TCPClient(8082);
????????client1.connect(“菜雞“);
????}
}
?屬性????????????大小?????日期????時(shí)間???名稱
-----------?---------??----------?-----??----
?????文件????????2692??2018-10-19?14:26??Server.java
?????文件????????2341??2018-10-19?14:26??Client.java
評(píng)論
共有 條評(píng)論