JAVA基於UDP的聊天程序


服務器端

import java.io.IOException;
import java.net.*;

public class UDPServer {

public static void main(String[] args) {
UDPServer frm=new UDPServer();

}
String strbuf=" ";
SerThread st;
public UDPServer(){
st=new SerThread();
st.start();
}

}


class SerThread extends Thread{
public SerThread(){

}
public void run(){
String str1;
try {
DatagramSocket skt=new DatagramSocket(8080);
System.out.println("服務器名:");
//顯示服務器名稱
System.out.println(InetAddress.getLocalHost().getHostName());
while (true){
byte[] inBuf =new byte[256];
//下面是取得服務器地址
DatagramPacket pkt;
//創建並設置接收pkt對象的接收信息
pkt=new DatagramPacket(inBuf,inBuf.length);
skt.receive(pkt);
//提取接收到的分組中的數據轉換為字符串
str1=new String(pkt.getData());
str1=str1.trim(); // 去掉字符串首尾空格

if(str1.length()>0){
int pot=pkt.getPort();
System.out.println("遠端端口"+pot);
System.out.println("服務器已接收到消息"+str1);

}
}
} catch (SocketException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
}

客戶端


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

public class UDPClient {

public static void main(String[] args) {
UDPClient frm=new UDPClient();
}

CliThread ct;
public UDPClient()
{
ct=new CliThread();
ct.start();
}
}


class CliThread extends Thread{
public CliThread(){

}

public void run(){
String str1;
String serverName="appledeMBP"; //服務器機器名
System.out.println("請發送消息給服務器《"+serverName+"》");
try {
DatagramSocket skt=new DatagramSocket();
DatagramPacket pkt;
while (true){
BufferedReader buf;
buf=new BufferedReader(new InputStreamReader(System.in));
System.out.println("請輸入信息:");
str1=buf.readLine();
byte[] outBuf=new byte[str1.length()];
outBuf=str1.getBytes();
//獲取服務器端地址
InetAddress address=InetAddress.getByName(serverName);

pkt=new DatagramPacket(outBuf,outBuf.length,address,8080);
skt.send(pkt);



}
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM