java编程 利用UDP方式,客户端向服务器发送三边值,服务器,根据三边值计算三角形面积返回客户端
创建两个类 分别添加main方法 一个作为server类一个作为client类
下面给你一个server和client的例子 你在基础上改一下就行了
client发送的时候发送三边值 server接收后 写一个计算三角形面积的函数 把接收到的三边值传入函数计算出结果作为数据返回到client端
/UDPServer
/
import javaio;
import javanet;
class UDPServer{
public static void main(String[] args)throws IOException{
DatagramSocket server = new DatagramSocket(5050);
byte[] recvBuf = new byte[100];
DatagramPacket recvPacket
= new DatagramPacket(recvBuf , recvBuflength);
serverreceive(recvPacket);
String recvStr = new String(recvPacketgetData() , 0 , recvPacketgetLength());
Systemoutprintln("Hello World!" + recvStr);
int port = recvPacketgetPort();
InetAddress addr = recvPacketgetAddress();
String sendStr = "Hello ! I'm Server";
byte[] sendBuf;
sendBuf = sendStrgetBytes();
DatagramPacket sendPacket
= new DatagramPacket(sendBuf , sendBuflength , addr , port );
serversend(sendPacket);
serverclose();
}
}/
UDPClient
/
import javaio;
import javanet;
class UDPClient{
public static void main(String[] args)throws IOException{
DatagramSocket client = new DatagramSocket();
String sendStr = "Hello! I'm Client";
byte[] sendBuf;
sendBuf = sendStrgetBytes();
InetAddress addr = InetAddressgetByName("127001");
int port = 5050;
DatagramPacket sendPacket
= new DatagramPacket(sendBuf ,sendBuflength , addr , port);
clientsend(sendPacket);
byte[] recvBuf = new byte[100];
DatagramPacket recvPacket
= new DatagramPacket(recvBuf , recvBuflength);
clientreceive(recvPacket);
String recvStr = new String(recvPacketgetData() , 0 ,recvPacketgetLength());
Systemoutprintln("收到:" + recvStr);
clientclose();
}
}
以下是一个展示java使用tcp通讯的简单例子,包括服务器和客户端代码:
/
TCPServer
/
import javaio;
import javanet;
class TCPServer{
public static void main(String[] args)throws IOException{
ServerSocket listen = new ServerSocket(5050);
Socket server = listenaccept();
InputStream in = servergetInputStream();
OutputStream out = servergetOutputStream();
char c = (char)inread();
Systemoutprintln("收到:" + c);
outwrite('s');
outclose();
inclose();
serverclose();
listenclose();
}
}
/
TCPClient
/
import javaio;
import javanet;
class TCPClient{
public static void main(String[] args)throws IOException{
Socket client = new Socket("127001" , 5050);
InputStream in = clientgetInputStream();
OutputStream out = clientgetOutputStream();
outwrite('c');
char c = (char)inread();
Systemoutprintln("收到:" + c);
outclose();
inclose();
clientclose();
}
}
你这消息头、消息体的结构格式都定下来了,总长度就是固定的啊?消息体的长度不是一共2+2+4+1=9个字节么?消息格式肯定要按照服务端的要求进行发送,明显服务端不是java的程序。。但是java里是没有Unsigned Integer这种数据类型的(java的stream操作里提供了一些unsigned的方法,或者自己写方法来生成对应的字节格式),你可以按照他的要求,使用字节数组封装好,然后发送。
针对这个示例消息,你可以:
创建一个长度为9的字节数组。把“9”变成byte放入前两个字节(前两个字节数据应该为:0x00, 0x09。这是第一个字段,长度),后面的字段数据以此类推。一个字段一个字段处理成服务器要求的格式。
然后把字节流发送给服务端。
Socket echoSocket = new Socket(hostName, portNumber);
final PrintWriter out = new PrintWriter(echoSocketgetOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(echoSocketgetInputStream()));
new Thread() {
public void run() {
while(true) {
outprintln ("hello");
try {
Threadsleep(601000);
} catch(Exception e) {}
}
}
}start();
String input;
while ((input= inreadLine()) != null) {
Systemoutprintln("echo: " + input);
}
服务器端和客户端都是通过SOCKET来进行通信的,首先产生一个 socket实例,通过这个实例,服务器端调用accept这个方法接收来自客户端发送的信息但是在产生socket实例的时候必须初始化一个端口用来负责接受客户端的请求!
客户端要给服务器发送消息也必须产生一个socket实例,初始化的时候必须指定服务器的IP地址,并且指定服务接收的端口号,这样客户端才能找到服务器要接收的地方,找到地方就可以发送过去了。和你写信一样。找到地址
BufferedReader in = new BufferedReader(new InputStreamReader(socketgetInputStream()));
PrintWriter out = new PrintWriter(socketgetOutputStream());
BufferedReader wt = new BufferedReader(new InputStreamReader(Systemin));
这个只是用来获取一个从键盘的一个流传送给服务器端的数据都是通过流来表示的。意思是是键盘输入的一个字节转化成字符流并输出或者写入!
程序分Server和Client
服务器端打开侦听的端口,一有客户端连接就创建两个新的线程来负责这个连接
一个负责客户端发送的信息(ClientMsgCollectThread 类),
另一个负责通过该Socket发送数据(ServerMsgSendThread )
Serverjava代码如下:
/
创建日期 2009-3-7
TODO 要更改此生成的文件的模板,请转至
窗口 - 首选项 - Java - 代码样式 - 代码模板
/
package faueMutiUser;
import javaioBufferedReader;
import javaioIOException;
import javaioInputStreamReader;
import javaioPrintWriter;
import javanetServerSocket;
import javanetSocket;
/
服务器端
@author Faue
/
public class Server extends ServerSocket {
private static final int SERVER_PORT = 10000;
/
构造方法,用于实现连接的监听
@throws IOException
/
public Server() throws IOException {
super(SERVER_PORT);
try {
while (true) {
Socket socket = superaccept();
new Thread(new ClientMsgCollectThread(socket), "getAndShow"
+ socketgetPort())start();
new Thread(new ServerMsgSendThread(socket), "send"
+ socketgetPort())start();
}
} catch (IOException e) {
eprintStackTrace();
}
}
public static void main(String[] args) throws IOException {
new Server();
}
/
该类用于创建接收客户端发来的信息并显示的线程
@author Faue
@version 100
/
class ClientMsgCollectThread implements Runnable {
private Socket client;
private BufferedReader in;
private StringBuffer inputStringBuffer = new StringBuffer("Hello");
/
得到Socket的输入流
@param s
@throws IOException
/
public ClientMsgCollectThread(Socket s) throws IOException {
client = s;
in = new BufferedReader(new InputStreamReader(client
getInputStream(), "GBK"));
}
public void run() {
try {
while (!clientisClosed()) {
inputStringBufferdelete(0, inputStringBufferlength());
inputStringBufferappend(inreadLine());
Systemoutprintln(getMsg(inputStringBuffertoString()));
}
} catch (IOException e) {
//eprintStackTrace();
Systemoutprintln(clienttoString() + " is closed!");
}
}
/
构造显示的字符串
@param line
@return
/
private String getMsg(String line) {
return clienttoString() + " says:" + line;
}
}
/
该类用于创建发送数据的线程
@author Faue
@version 100
/
class ServerMsgSendThread implements Runnable {
private Socket client;
private PrintWriter out;
private BufferedReader keyboardInput;
private StringBuffer outputStringBuffer = new StringBuffer("Hello");
/
得到键盘的输入流
@param s
@throws IOException
/
public ServerMsgSendThread(Socket s) throws IOException {
client = s;
out = new PrintWriter(clientgetOutputStream(), true);
keyboardInput = new BufferedReader(new InputStreamReader(Systemin));
}
public void run() {
try {
while (!clientisClosed()) {
outputStringBufferdelete(0, outputStringBufferlength());
outputStringBufferappend(keyboardInputreadLine());
outprintln(outputStringBuffertoString());
}
} catch (IOException e) {
//eprintStackTrace();
Systemoutprintln(clienttoString() + " is closed!");
}
}
}
}
客户端:
实现基于IP地址的连接,连接后也创建两个线程来实现信息的发送和接收
/
创建日期 2009-3-7
/
package faueMutiUser;
import javaioBufferedReader;
import javaioIOException;
import javaioInputStreamReader;
import javaioPrintWriter;
import javanetSocket;
/
客户端
@author Faue
/
public class Client {
private Socket mySocket;
/
创建线程的构造方法
@param IP
@throws IOException
/
public Client(String IP) throws IOException {
try {
mySocket = new Socket(IP, 10000);
new Thread(new ServerMsgCollectThread(mySocket), "getAndShow"
+ mySocketgetPort())start();
new Thread(new ClientMsgSendThread(mySocket), "send"
+ mySocketgetPort())start();
} catch (IOException e) {
//eprintStackTrace();
Systemoutprintln("ServerIP:" + IP
+ " port:10000 can not be Connected");
}
}
public static void main(String[] args) throws IOException {
try {
new Client(args[0]);
} catch (Exception e) {
Systemoutprintln("输入的IP地址错误");
}
}
/
该类用于创建接收服务端发来的信息并显示的线程
@author Faue
@version 100
/
class ServerMsgCollectThread implements Runnable {
private Socket client;
private BufferedReader in;
private StringBuffer inputStringBuffer = new StringBuffer("Hello");
/
得到Socket的输入流
@param s
@throws IOException
/
public ServerMsgCollectThread(Socket s) throws IOException {
client = s;
in = new BufferedReader(new InputStreamReader(client
getInputStream(), "GBK"));
}
public void run() {
try {
while (!clientisClosed()) {
inputStringBufferdelete(0, inputStringBufferlength());
inputStringBufferappend(inreadLine());
Systemoutprintln(getMsg(inputStringBuffertoString()));
}
} catch (IOException e) {
//eprintStackTrace();
Systemoutprintln(clienttoString() + " is closed!");
Systemexit(0);
}
}
/
构造输入字符串
@param line
@return
/
private String getMsg(String line) {
return clienttoString() + " says:" + line;
}
}
/
该类用于创建发送数据的线程
@author Faue
@version 100
/
class ClientMsgSendThread implements Runnable {
private Socket client;
private PrintWriter out;
private BufferedReader keyboardInput;
private StringBuffer outputStringBuffer = new StringBuffer("Hello");
/
得到键盘的输入流
@param s
@throws IOException
/
public ClientMsgSendThread(Socket s) throws IOException {
client = s;
out = new PrintWriter(clientgetOutputStream(), true);
keyboardInput = new BufferedReader(new InputStreamReader(Systemin));
}
public void run() {
try {
while (!clientisClosed()) {
outputStringBufferdelete(0, outputStringBufferlength());
outputStringBufferappend(keyboardInputreadLine());
outprintln(outputStringBuffertoString());
}
outprintln("--- See you, bye! ---");
} catch (IOException e) {
//eprintStackTrace();
Systemoutprintln(clienttoString() + " is closed!");
Systemexit(0);
}
}
}
}
如果对您有帮助,请记得采纳为满意答案,谢谢!祝您生活愉快!
vaela
使用Socket可以做到,不过直接编程一般都是在局域网内,如果要在不同局域网间通信,需要使用一台有公网IP的服务器,可以电脑A和电脑B同时连接服务器,然后A向服务器传递文件,服务器再将文件转发电脑B。也可以使用打洞的方式使A、B互联,此时服务器的作用是辅助打洞。A、B向服务器发送信息后socket不要关闭(假设使用10989端口),同时使用Serversocket绑定监听相同的端口(监听10989端口)。在java中有参数可以做到,具体方法请自行百度。服务器获取到A、B的外网地址和端口,将A的外网地址信息发送给B、将B的外网地址信息发送给A。然后使用A没有关闭的Socket向B发送一组信息(此时连接会失败,但是B的路由表上已经记录了A的信息),发送后A向服务器发送消息,服务器告诉B A已经发送消息。然后B使用未关闭的socket向A发送消息,就和A上监听的ServerSocket取得连接了。之后就可以互相传递数据。
0条评论