JAVA点对点聊天代码portjava.net.DatagramPacket;importjava.net.DatagramSocket;importjava.net.InetAddress;publicclassUDPSendTest{voiddisplay(){bytebuf[]=newbyte[256];Datagra...
JAVA 点对点聊天代码
port java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPSendTest
{
void display()
{
byte buf[]=new byte[256];
DatagramPacket sPacket;
DatagramPacket rPacket;
DatagramSocket socket;
int count;
byte[] host=new byte[128];
try
{
socket=new DatagramSocket();
//输入目的方的主机名
System.out.print("请输入目的方的主机名: ");
count=System.in.read(host);
InetAddress addr=InetAddress.getByName(new String(host,0,count-2));
while (true)
{
System.out.print("请输入要发送的数据: ");
count=System.in.read(buf);
//发送数据报
sPacket=new DatagramPacket(buf,count-2,addr,8888);
socket.send(sPacket);
//接收数据报
rPacket=new DatagramPacket(buf,buf.length);
socket.receive(rPacket);
System.out.print("返回信息: ");
String str=new String(rPacket.getData(),0,rPacket.getLength());
System.out.println(str);
}
}
catch (Exception e)
{
System.out.println(e);
}
}
public static void main(String[] args)
{
UDPSendTest app=new UDPSendTest();
app.display();
}
}
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class UDPReceiveTest
{
void display()
{
byte buf[]=new byte[256];
DatagramPacket sPacket;
DatagramPacket rPacket;
DatagramSocket socket;
int count;
byte[] res="OK".getBytes();
try
{
socket=new DatagramSocket(8888);
while (true)
{
rPacket=new DatagramPacket(buf,buf.length);
//接收数据报
socket.receive(rPacket);
//获取发送方的地址
InetAddress addr=rPacket.getAddress();
//获取发送方的端口
int port=rPacket.getPort();
count=rPacket.getLength();
System.out.println("接收到来自 "+addr.getHostAddress()+" 数据:");
System.out.println(new String(buf,0,count));
//发送数据报
sPacket=new DatagramPacket(res,res.length,addr,port);
socket.send(sPacket);
}
}
catch (Exception e)
{
System.out.println(e);
}
}
public static void main(String[] args)
{
UDPReceiveTest app=new UDPReceiveTest();
app.display();
}
}
这个是UDP模式的 现要求一个TCP的 要求直接能运行的
3楼那个大哥 我给那么大段一个完整的代码 很明显是想让你在那个上改么
展开