datagramsocket和socket的区别及使用场景
// 服务器端
try {
serversocket serversocket = new serversocket(8080);
socket socket = serversocket.accept();
// 从客户端接收数据
inputstream inputstream = socket.getinputstream();
bufferedreader reader = new bufferedreader(new inputstreamreader(inputstream));
string message = reader.readline();
system.out.println("收到客户端消息:" message);
// 向客户端发送数据
outputstream outputstream = socket.getoutputstream();
printwriter writer = new printwriter(outputstream, true);
writer.println("欢迎连接服务器!");
socket.close();
serversocket.close();
} catch (ioexception e) {
e.printstacktrace();
}
// 客户端
try {
socket socket = new socket("localhost", 8080);
// 向服务器发送数据
outputstream outputstream = socket.getoutputstream();
printwriter writer = new printwriter(outputstream, true);
writer.println("hello, server!");
// 从服务器接收数据
inputstream inputstream = socket.getinputstream();
bufferedreader reader = new bufferedreader(new inputstreamreader(inputstream));
string message = reader.readline();
system.out.println("收到服务器消息:" message);
// 服务器端
try {
datagramsocket serversocket = new datagramsocket(8080);
// 接收客户端发送的数据
byte[] receivebuffer = new byte[1024];
datagrampacket receivepacket = new datagrampacket(receivebuffer, receivebuffer.length);
serversocket.receive(receivepacket);
string message = new string(receivepacket.getdata(), 0, receivepacket.getlength());
system.out.println("收到客户端消息:" message);
// 向客户端发送数据
byte[] sendbuffer = "欢迎连接服务器!".getbytes();
datagrampacket sendpacket = new datagrampacket(sendbuffer, sendbuffer.length, receivepacket.getaddress(), receivepacket.getport());
serversocket.send(sendpacket);
serversocket.close();
} catch (ioexception e) {
e.printstacktrace();
}
// 客户端
try {
datagramsocket clientsocket = new datagramsocket();
// 向服务器发送数据
byte[] sendbuffer = "hello, server!".getbytes();
datagrampacket sendpacket = new datagrampacket(sendbuffer, sendbuffer.length, inetaddress.getlocalhost(), 8080);
clientsocket.send(sendpacket);
// 接收服务器发送的数据
byte[] receivebuffer = new byte[1024];
datagrampacket receivepacket = new datagrampacket(receivebuffer, receivebuffer.length);
clientsocket.receive(receivepacket);
string message = new string(receivepacket.getdata(), 0, receivepacket.getlength());
system.out.println("收到服务器消息:" message);
clientsocket.close();
} catch (ioexception e) {
e.printstacktrace();
}
请后发表内容