Java网络编程:UDP(实现String字符串中两个整数的四则运算)
运行截图如下:
serverside
Response.java
代码如下:
package serverside;
import java.io.IOException;
import java.net.*;
import java.util.Stack;
/**
* The serverside, which shall be runned first.
* Functions:
* 1. receive the packet sended by clientside
* 2. print the received request and the result (e.g. Server: 5*4=20)
* 3. reply with the result of the calculation (as a string, e.g. 777+888=1665)
*
* @author ChangCHEN
*
*/
public class Response {
public static void main(String[] args) throws Exception {
//1. create a socket and open the port
DatagramSocket socket = new DatagramSocket(6666);
try{
//2. receive packet1
byte[] container = new byte[10];
DatagramPacket packet1 = new DatagramPacket(container,0 ,container.length);
socket.receive(packet1);
//3. trim the data and make them as string
String receiveData = trimDataToString(packet1);
//4. parse the string and print left&right number on the console
int result = parseStringToResult(receiveData);
//5.print the result on the console
System.out.println("Server: "+receiveData+"="+result);
//6.send packet2
String str = receiveData + "=" + result;
DatagramPacket packet2 = new DatagramPacket(str.getBytes(),0 ,str.getBytes().length,new InetSocketAddress("localhost",2020));
socket.send(packet2);
}catch (Exception e) {
e.printStackTrace();
}finally {
if(socket!=null) {
try{
socket.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
/**
* Parse the receive data (String) by the operator, left number and right number
* @param receiveData the string form of data typed in by the clientside
* @return the result of the expression in the int form
*/
private static int parseStringToResult(String receiveData) {
int result = 0;
Stack<Object> stack = new Stack<>();
for(int i=0;i<receiveData.length();++i) {
if(receiveData.charAt(i)=='*') {
int leftNum = 0;
int rightNum = 0;
for(int j = (i-1);j>=0;j--) {
leftNum = (int) (leftNum + (Math.pow(10, (i-1-j)))*Integer.valueOf(String.valueOf(receiveData.charAt(j))));
}
// System.out.println("leftNum "+leftNum);
int p = receiveData.length()-i-2;
for(int j=0; p-j>=0;j++ ) {
rightNum = (int) (rightNum + Integer.valueOf(String.valueOf(receiveData.charAt(i+j+1)))*(Math.pow(10, (p-j))));
}
// System.out.println("rightNum "+rightNum);
result= leftNum*rightNum;
}else if(receiveData.charAt(i)=='/') {
int leftNum = 0;
int rightNum = 0;
for(int j = (i-1);j>=0;j--) {
leftNum = (int) (leftNum + (Math.pow(10, (i-1-j)))*Integer.valueOf(String.valueOf(receiveData.charAt(j))));
}
// System.out.println("leftNum "+leftNum);
int p = receiveData.length()-i-2;
for(int j=0; p-j>=0;j++ ) {
rightNum = (int) (rightNum + Integer.valueOf(String.valueOf(receiveData.charAt(i+j+1)))*(Math.pow(10, (p-j))));
}
// System.out.println("rightNum "+rightNum);
result= leftNum/rightNum;
}else if(receiveData.charAt(i)=='+') {
int leftNum = 0;
int rightNum = 0;
for(int j = (i-1);j>=0;j--) {
leftNum = (int) (leftNum + (Math.pow(10, (i-1-j)))*Integer.valueOf(String.valueOf(receiveData.charAt(j))));
}
// System.out.println("leftNum "+leftNum);
int p = receiveData.length()-i-2;
for(int j=0; p-j>=0;j++ ) {
rightNum = (int) (rightNum + Integer.valueOf(String.valueOf(receiveData.charAt(i+j+1)))*(Math.pow(10, (p-j))));
}
// System.out.println("rightNum "+rightNum);
result= leftNum+rightNum;
}else if(receiveData.charAt(i)=='-') {
int leftNum = 0;
int rightNum = 0;
for(int j = (i-1);j>=0;j--) {
leftNum = (int) (leftNum + (Math.pow(10, (i-1-j)))*Integer.valueOf(String.valueOf(receiveData.charAt(j))));
}
// System.out.println("leftNum "+leftNum);
int p = receiveData.length()-i-2;
for(int j=0; p-j>=0;j++ ) {
rightNum = (int) (rightNum + Integer.valueOf(String.valueOf(receiveData.charAt(i+j+1)))*(Math.pow(10, (p-j))));
}
// System.out.println("rightNum "+rightNum);
result= leftNum-rightNum;
}else {
int x = Integer.valueOf(String.valueOf(receiveData.charAt(i)));
stack.push(x);
}
}
return result;
}
/**trim the data, cut the clutters generated by the large container
* @param packet1 the datagrampacket sended by the clientside
* @return a string of data which is trimmed
*/
private static String trimDataToString(DatagramPacket packet1) {
byte[] data = packet1.getData();
int k=0;
while(data[k]!=0) {
k++;
}
String receiveData = new String(data,0,k);
return receiveData;
}
}
clientside
Request.java
代码如下:
package clientside;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
/**
* The client side, which shall be runned after.
* Functions:
* 1.Sends a request (given by user input, ask the user!) for calculation to the server (as a string, e.g. 5*4, 6-2, 3+189, 12/8)
* 2.Receive the result
* 3.print the same thing as the server. (e.g. Client: 5*4=20)
*
* @author ChangCHEN
*
*/
public class Request {
public static void main(String[] args) throws Exception {
//1. create a socket and open the port
DatagramSocket socket = new DatagramSocket(2020);
//2. type in the data: Console reads
try {
System.out.println("Please type in an integer four operations expression with two operands: ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String sendData = reader.readLine();
//3. send packet1
DatagramPacket packet1 = new DatagramPacket(sendData.getBytes(),0,sendData.getBytes().length,new InetSocketAddress("localhost",6666));
socket.send(packet1);
//4. receive packet2
byte[] container = new byte[1024];
DatagramPacket packet2 = new DatagramPacket(container,0 ,container.length);
socket.receive(packet2);
//5. read packet2
String receiveData = new String(packet2.getData(),0,packet2.getData().length);
System.out.println("Client: "+receiveData);
} catch (SocketException e) {
e.printStackTrace();
}finally {
//6. close the socket
if(socket!=null) {
try{
socket.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
实现单字节两数的四则运算
clientside
Receive.java
代码如下:
package serverside;
import java.net.*;
import java.util.Stack;
public class Receive {
public static byte[] toBytes(int number){
byte[] bytes = new byte[4];
bytes[0] = (byte)number;
bytes[1] = (byte) (number >> 8);
bytes[2] = (byte) (number >> 16);
bytes[3] = (byte) (number >> 24);
return bytes;
}
public static void main(String[] args) throws Exception {
//1. open the port
DatagramSocket socket = new DatagramSocket(6666);
try{
//2. receive packet
byte[] container = new byte[3];
DatagramPacket packet = new DatagramPacket(container,0 ,container.length);
socket.receive(packet);
byte[] data = packet.getData();
String receiveData = new String(data,0,data.length);
System.out.println("The answer is: ");
//3. use algorithm to parse the string and print the result on the console
int result = 0;
Stack<Object> stack = new Stack<>();
for(int i=0;i<receiveData.length();++i) {
if(receiveData.charAt(i)>='0'&&receiveData.charAt(i)<='9') {
int x = Integer.valueOf(String.valueOf(receiveData.charAt(i)));
if(stack.isEmpty()) {
stack.push(x);
}else {
if((char)stack.peek()=='*') {
stack.pop();
int y=(int)stack.pop();
result=(y*x);
System.out.println(receiveData+"="+result);
}else if((char)stack.peek()=='/'){
stack.pop();
int y=(int)stack.pop();
result=(y/x);
System.out.println(receiveData+"="+result);
}else if((char)stack.peek()=='+'){
stack.pop();
int y=(int)stack.pop();
result=(y+x);
System.out.println(receiveData+"="+result);
}else if((char)stack.peek()=='-'){
stack.pop();
int y=(int)stack.pop();
result=(y-x);
System.out.println(receiveData+"="+result);
}
}
}else if(receiveData.charAt(i)=='+') {
stack.push('+');
}else if(receiveData.charAt(i)=='-') {
stack.push('-');
}else if(receiveData.charAt(i)=='*') {
stack.push('*');
}else if(receiveData.charAt(i)=='/') {
stack.push('/');
}
}
//3.Prepare the data: result and the packet2
byte[] bytes = toBytes(result);
DatagramPacket packet2 = new DatagramPacket(bytes,0 ,bytes.length,new InetSocketAddress("localhost",2020));
//4. send the packet2
socket.send(packet2);
}catch (Exception e) {
e.printStackTrace();
}finally {
socket.close();
}
}
}
serverside
Send.java
package clientside;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.*;
public class Send {
public static int toInt(byte[] bytes){
int number = 0;
for(int i = 0; i < 4 ; i++){
number += bytes[i] << i*8;
}
return number;
}
public static void main(String[] args) throws Exception {
//1. create a socket
DatagramSocket socket = new DatagramSocket(2020);
try {
System.out.println("Please type in the caculation: ");
//2. Prepare the data: Console reads System.in
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String data = reader.readLine();
byte[] datas = data.getBytes();
DatagramPacket packet = new DatagramPacket(datas,0,datas.length,new InetSocketAddress("localhost",6666));
//3. send the packet
socket.send(packet);
//4. receive packet2
byte[] container = new byte[4];
DatagramPacket packet2 = new DatagramPacket(container,0 ,container.length);
socket.receive(packet2);
byte[] data2 = packet2.getData();
int result = toInt(data2);
System.out.println("The answer is: "+data+"="+result);
} catch (SocketException e) {
e.printStackTrace();
}finally {
socket.close();
}
}
}