📄 udpclient.java
字号:
import java.io.*;
import java.net.*;
public class udpclient
{
public static void main(String[] args) throws IOException
{
DatagramSocket clientsoc=null;//客户的socket
DatagramPacket clientpac=null;//客户发出去的数据包
DatagramPacket clientrecpac=null;//客户从服务器上接收的数据包
String strToSend=null;//要发给服务器的数据
String data=null;//接收的字节流
byte[] buf=null;//发送的字节流
byte[] buf1=null;//发送的最后一个字节流
byte[] bufrec=null;//接收的字节流
DataInputStream sysin=null;//客户的输入流
try
{
bufrec=new byte[256];
clientsoc=new DatagramSocket();
sysin=new DataInputStream(System.in);
strToSend=sysin.readLine();
while(strToSend!="quit")
{
buf=new byte[strToSend.length()];
strToSend.getBytes(0,buf.length,buf,0);
clientpac=new DatagramPacket(buf,buf.length,InetAddress.getByName("localhost"),9000);
clientsoc.send(clientpac);
clientrecpac=new DatagramPacket(bufrec,bufrec.length);
clientsoc.receive(clientrecpac);
data=new String(bufrec,0,0,bufrec.length);
System.out.println("Server said:"+data);
strToSend=sysin.readLine();
}
buf1=new byte[strToSend.length()];
strToSend.getBytes(0,buf1.length,buf1,0);
clientpac=new DatagramPacket(buf1,buf1.length,InetAddress.getByName("localhost"),9000);
clientsoc.send(clientpac);
}
catch(Exception e)
{
System.out.println("Error:"+e);
}
finally
{
clientsoc.close();
System.exit(0);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -