java中socket编程
各们大神们,小弟在java中想以UDP的方式发送一条字符串给服务器,但是之前没用到过这方面的知识,还请大神们帮帮忙,写一个客户端的例子,只要客户端就行了。现在我详细介绍下...
各们大神们,小弟在java中想以UDP的方式发送一条字符串给服务器,但是之前没用到过这方面的知识,还请大神们帮帮忙,写一个客户端的例子,只要客户端就行了。现在我详细介绍下:首先:我发一个字符串到服务器(比如:发“F6”),服务器接收到我发的这个字符串(F6)之后,会返回给我一个字符串(比如:“abc123”),我要把这个服务器返回给我的字符串截取出来,用个数组存起来。这样我这边的工作就算完成了。各位大神帮忙啊,谢谢!
展开
1个回答
2013-12-01
展开全部
import java.io.*;
import java.net.*;
class UDPClient{
public static void main(String args[]) throws Exception{
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = "F6".getBytes();
byte[] receiveData = new byte[64];
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
请参考
import java.net.*;
class UDPClient{
public static void main(String args[]) throws Exception{
DatagramSocket clientSocket = new DatagramSocket();
InetAddress IPAddress = InetAddress.getByName("localhost");
byte[] sendData = "F6".getBytes();
byte[] receiveData = new byte[64];
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}
}
请参考
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询