`

java -> UDP Server/Client

    博客分类:
  • java
 
阅读更多

 

UDPServer, 异步返回。新建线程返回数据

package m;
import java.io.*;
import java.net.*;
import java.util.ArrayList;



public class UDPServer extends Thread
{

	
	/**
	 * 
	 */
	private static int server_port = 9988;
	//private static final long serialVersionUID = 8362159773100396897L;
	private static DatagramSocket serverSocket;  
	public static String name;

 
	//send method 2
	public static void sendUDPPacket2(String info , InetAddress IP , int port) throws InterruptedException
	{ 
		byte[] sendData = new byte[4096];
		sendData = info.getBytes();  
		try 
		{
 
				DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length, IP, port);
				serverSocket.send(sendPacket);
				
 
				
				
				
		}
		catch (SocketException e) 
		{
			
			// TODO Auto-generated catch block
			 e.printStackTrace();
		} 
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			

			 e.printStackTrace();
		}
		
	}
	
	 
	//Receiver thread
	public void startReceiving()
	{
		Thread tReceiverthread = new Thread(new Runnable()
		{
			@Override
			public void run() 
			{
				try 
				{
					UDPReceiver();

				} 
				catch (Exception e) 
				{
					// e.printStackTrace();
				}
			}
	

			public void UDPReceiver() throws Exception
			{
				 
				while(true)
				{
			
			 
					byte[] receiveData1 = new byte[8192];
					final DatagramPacket receivePacket1 = new DatagramPacket(receiveData1, receiveData1.length);	
					try {
						serverSocket.receive(receivePacket1);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
   
					new Thread() {  
				        @Override  
				        public void run() {  
				            // TODO Auto-generated method stub  
				            if (!Thread.currentThread().isInterrupted()) {// 如果没有终止  
				                try {  
									String receive_str = new String(receivePacket1.getData());
									print("RECEIVE:"+receive_str+"\n");
									//打印当前线程总数
									print("ThreadCount:"+Thread.activeCount()+"");
									
									//send 
									final InetAddress IPAddress =receivePacket1.getAddress();
									final int port = receivePacket1.getPort();
									//
				                	Thread.sleep(10000);
				                    // do something  
				                	sendUDPPacket2("ssssssssss", IPAddress , port);
				                	
				                	Thread.currentThread().interrupt(); 
				                } catch (Exception e) {  
				                    e.printStackTrace();  
				                } finally {  
				                    Thread.currentThread().interrupt();// 执行完终止  
				                }  
				            }  
				        }  
				    }.start();
					 
					
								
				}//end of while loop
				
			}//end of receiver function
	
		});//end of runnable
		
		tReceiverthread.start();
		System.out.println("Thread started");
	}//end of startReceiver
		
	
	
	public static void print(String s){
		System.out.println(s+"\n");
	}
	
	public static void main(String[] args) throws Exception
	{
		// TODO Auto-generated method stub
 
		serverSocket = new DatagramSocket(server_port);
		System.out.println("Server has been started\n");
		new UDPServer().startReceiving();
 
	}//main
}//class
			

 

 

 

 

 

UDPServer.java

package bidding;
import java.io.*;
import java.net.*;
import java.util.ArrayList;



public class UDPServer extends Thread
{

	
	/**
	 * 
	 */
	//private static final long serialVersionUID = 8362159773100396897L;
	private static DatagramSocket serverSocket;
	public static boolean ACK = false;
	public static ArrayList<client> clientList = new ArrayList<client>();
	public static ArrayList<offline_user> offline_List = new ArrayList<offline_user>();
	public static ArrayList<Item> itemList = new ArrayList<Item>();
	public static String name;

	/**
	 * 
	 */
	public static void sendACK(InetAddress IP,int port)
	{
		System.out.println("Sent ack");
		byte[] data = new byte[4096];
		data = "acknowledgement".getBytes();
		DatagramPacket sendPacket = new DatagramPacket(data,data.length, IP, port);
		try {
			serverSocket.send(sendPacket);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
		
		
	}
	//Used to broadcast client information
	public static ArrayList<String> clientInfo()
	{
		ArrayList<String> info = new ArrayList<String>();
		for(int i = 0; i < clientList.size() ; i++)
		{
			client c = clientList.get(i);
			String s = c.username+" "+c.cli_IP+" "+c.cli_port;
			info.add(s);
		}
		return info;
	}
	
	//send method
	public static void sendUDPPacket(String info , InetAddress IP , int port, String name) throws InterruptedException
	{
		System.out.println("Sending " + info);
		int i;
		for(i=0;i<clientList.size();i++)
		{
			client c =clientList.get(i);
			if(c.username.equalsIgnoreCase(name))
			{
				break;
			}
		}
		if (i == clientList.size())
		{
			info = "Offline message: "+info;
			offline_user o = new offline_user(name,info);
			offline_List.add(o);
			return;
		}
		byte[] sendData = new byte[4096];
		sendData = info.getBytes();
		int attempt_no = 0;
		//ACK =false;
		try 
		{

		/*while ((!ACK && attempt_no < 5)) 
			{*/
				System.out.println("Sending : "+info);
				System.out.println(ACK);
				DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length, IP, port);
				serverSocket.send(sendPacket);
				/*Thread.sleep(500);
				if(!ACK)
					sendAttempt++;
				System.out.println("sendAttemptCount: " + attempt_no);*/
		//	}
				
			/*if(!ACK)
				addOfflineMessage(name,info);
			for(int i=0;i<clientList.size();i++)
			{
				client c = clientList.get(i);
				if(c.username.equals(name))
				{
					clientList.remove(i);
					break;
				}
			}*/
				
				
				
				
		}
		catch (SocketException e) 
		{
			
			// TODO Auto-generated catch block
			 e.printStackTrace();
		} 
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			

			 e.printStackTrace();
		}
		
	}

	/**
	 * @param args
	 */
	//FInds the name of the user from whom the packet has been received
	public static String getCurrentUser(InetAddress IP, int port)
	{
			client c = new client();
			for(int i=0;i<clientList.size();i++)
			{
				c = clientList.get(i);
				
			}
		for(int i=0; i < clientList.size();i++)
		{
			c = clientList.get(i);
			if((c.cli_IP.toString().equals(IP.toString())) && (c.cli_port == port))
			{
				return c.username;
			}
		}
		return "none";
	}
	
	//add messagesfor offline users
	public static void addOfflineMessage(String username, String message)
	{
		System.out.println("Inside offline messages");
		
		offline_user o = new offline_user(username,message);
		offline_List.add(o);
		
		for(int j = 0; j<offline_List.size();j++)
		{
			offline_user o1 = offline_List.get(j);
			System.out.println("Offline message " + username +" "+message);
		}
	}
	
	//Receiver thread
	public void startReceiving()
	{
		Thread tReceiverthread = new Thread(new Runnable()
		{
			@Override
			public void run() 
			{
				try 
				{
					UDPReceiver();

				} 
				catch (Exception e) 
				{
					// e.printStackTrace();
				}
			}
	

			public void UDPReceiver() throws Exception
			{
				
				int itemCount = 0;
				while(true)
				{
			
					boolean flag1 = false;
					String message;
					String reply;
					byte[] receiveData1 = new byte[8192];
					DatagramPacket receivePacket1 = new DatagramPacket(receiveData1, receiveData1.length);	
					try {
						serverSocket.receive(receivePacket1);
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					InetAddress IPAddress =receivePacket1.getAddress();
					int port = receivePacket1.getPort();
					String command = new String(receivePacket1.getData());
					String currentuser = getCurrentUser(IPAddress,port);
					System.out.println("The current user is"+currentuser);
					String[] split_command1 = new String[20];
					split_command1 = command.split(" ");
							
					System.out.println("Printing the list of users");
					for(int i=0; i<clientList.size();i++)
					{
						client c = clientList.get(i);
						System.out.println(c.username);
					}
					
					
					
					if(command.trim().equals("acknowledgement"))
					{
						System.out.println("Acknowledgement received");
						ACK = true;
					}
				
					else if(split_command1[0].trim().equals("register"))
					{
						name = split_command1[1].trim();
						System.out.println("Entered registered part");
						System.out.println(clientList.isEmpty());
						if(!clientList.isEmpty())
						{
							
							for (int i=0; i <clientList.size(); i++)
							{
								client c = clientList.get(i);
								if(c.username.equalsIgnoreCase(name))
								{
									clientList.remove(i);
								}
							}
						}
						
						client CL = new client(name,IPAddress,port);
						System.out.println("Adding user");
						clientList.add(CL);
						
						sendACK(IPAddress,port);
									
						
						
						if(!offline_List.isEmpty())
						{
							for(int i=0;i<offline_List.size();i++)
							{
								offline_user u = offline_List.get(i);
								System.out.println(u.name);
								System.out.println(u.message);
							}
							System.out.println("Entered offline messages list");
							for (int i=0; i <offline_List.size(); i++)
							{
								offline_user u = offline_List.get(i);
								System.out.println(u.name);
								if(u.name.equalsIgnoreCase(name))
								{
									sendUDPPacket(u.message,IPAddress,port,name);
									
								}
							}
							
						}
						sendUDPPacket("done",IPAddress,port,name);
											
						for(int i=0 ; i<clientList.size(); i++)
						{
							System.out.println("Entered broadcast");
							client c = clientList.get(i);
							sendUDPPacket("broadcast",c.cli_IP,c.cli_port,c.username);
							ArrayList<String> client_info = new ArrayList<String>();
							client_info = clientInfo();
							System.out.println(client_info.toString());
							sendUDPPacket(client_info.toString(),c.cli_IP, c.cli_port,c.username);
							sendUDPPacket("sent",c.cli_IP,c.cli_port,c.username);
							
						}
						
						
						//sendUDPPacket("updated",IPAddress,port,name);
					}
					
					else if(split_command1[0].trim().equals("sell"))
					{
						
						System.out.println("Entered the sell part");
						String itemname = split_command1[1];
					
						int trans_limit = Integer.parseInt(split_command1[2]);
						int start_bid = Integer.parseInt(split_command1[3]);
						System.out.println(start_bid);
						int buy_now = Integer.parseInt(split_command1[4]);
						String description = split_command1[5];
					
					
						if((trans_limit > 0) && (start_bid >= 0) && (start_bid >0) )
						{
							itemCount = itemCount + 1;
							Item item = new Item(itemCount,itemname,currentuser,trans_limit,start_bid,buy_now,description);
							itemList.add(item);
							reply = "["+itemname+" added with number "+item.item_code+"]";
													
						}
						else
						{
							reply = "[ Error : arguments ]";
						}
						sendUDPPacket(reply,IPAddress,port,name);
					
					}
				
					else if(split_command1[0].trim().equals("deregister"))
					{
						
						int index = -1;
						for(int i=0 ; i < clientList.size(); i++ )
						{
							client c = clientList.get(i);
							if(c.username.equals(currentuser))
							{
								System.out.println(i);
								index = i;
							}
						}
					
						clientList.remove(index);
						sendACK(IPAddress,port);
						for(int i=0 ; i<clientList.size(); i++)
						{
							System.out.println("Entered broadcast");
							client c = clientList.get(i);
							sendUDPPacket("broadcast",c.cli_IP,c.cli_port,c.username);
							ArrayList<String> client_info = new ArrayList<String>();
							client_info = clientInfo();
							System.out.println(client_info.toString());
							sendUDPPacket(client_info.toString(),c.cli_IP, c.cli_port,c.username);
							sendUDPPacket("sent",c.cli_IP,c.cli_port,c.username);
							
						}
						
					
					}
				
					else if(split_command1[0].trim().equals("info"))
					{
						System.out.println("Entered info");
						if(split_command1.length > 1)
						{
							int i;
							for(i = 0; i < itemList.size();i++)
							{
								Item it = itemList.get(i);
								if(Integer.parseInt(split_command1[1].trim()) == it.item_code)
								{
									String response = it.get_info();
									sendUDPPacket(response,IPAddress,port,currentuser);
									break;
								}
							}
							if ( i == itemList.size())
							{
								String response = "[Error: "+Integer.parseInt(split_command1[1].trim())+" item not found]";
								sendUDPPacket(response,IPAddress,port,currentuser);
													
							}
						}
						else 
						{
							if(itemList.isEmpty())
							{
								String response = "[Error : empty]";
								sendUDPPacket(response,IPAddress,port,currentuser);
																			
							}
							else
							{
								
								for(int i=0; i< itemList.size();i++)
								{
									Item I = itemList.get(i);
									String response = I.get_info();
									System.out.println(response);
									sendUDPPacket(response,IPAddress,port,currentuser);
			
								}
								
							}
							
							sendUDPPacket("done",IPAddress,port,currentuser);
												
						}
						
					}//else if of info ends
					
					
					else if(split_command1[0].trim().equals("bid"))
					{
						
						System.out.println("Entered bid");
						for(int i = 0; i < itemList.size(); i++)
						{
							Item it = itemList.get(i); 
							if(Integer.parseInt(split_command1[1].trim()) == it.item_code)
							{
								if(currentuser.equals(it.owner))
								{
									String response = "[ Error : owner ]";
									sendUDPPacket(response,IPAddress,port,currentuser);
									flag1 = true;
								}
								else if(currentuser.equals(it.buyername))
								{
									String response = "[ Error : duplicate bid ]";
									sendUDPPacket(response,IPAddress,port,currentuser);
									flag1 = true;
								}
								else if(Integer.parseInt(split_command1[2].trim()) < 0)
								{
									String response = "[ Error : negative bid ]";
									sendUDPPacket(response,IPAddress,port,currentuser);
									flag1 = true;
								}
								else
								{
									int amount = Integer.parseInt(split_command1[2].trim());
									amount = amount + it.current_bid;
									it.set_current_bid(amount);
									it.set_buyername(currentuser);
									it.transaction_count++;
									
							
									if((it.transaction_count == it.translimit) || (it.current_bid >= it.buynow))
									{
										int j;
										String response = "[ purchased :"+it.item_code+" "+it.name+" "+it.current_bid+" ]";
										sendUDPPacket(response,IPAddress,port,currentuser);
										
								
										for(j = 0; j< clientList.size();j++)
										{
											client c = clientList.get(j);
											if(it.owner.equals(c.username))
											{
												String response1 = "[ sold :"+it.item_code+" "+it.name+" "+it.current_bid+" ]";
												sendUDPPacket(response1,c.cli_IP,c.cli_port,c.username);
												
											}
										}
										
										
										
										itemList.remove(i);
										flag1 = true;
									}
									else
									{
										String response = it.item_code+" "+it.name+" "+it.current_bid;
										sendUDPPacket(response,IPAddress,port,currentuser);
										flag1 = true;
									}
									
								}
								
							}
						
						}
					
						if(flag1 == false)
						{
							String response = "Item not found";
							sendUDPPacket(response,IPAddress,port,currentuser);
							
						}
					}//else if for bid ends here
					
					else if(split_command1[0].trim().equals("direct"))
					{
						System.out.println("Entered direct");
						String buyerName = split_command1[2].trim();
						System.out.println(buyerName);
						InetAddress buyer_IP = null;
						int buyer_port = 0;
						int item_Code = Integer.parseInt(split_command1[1].trim());
						System.out.println(item_Code);
						int j;
						for(j=0;j<clientList.size();j++)
						{
							client c = clientList.get(j);
							if(buyerName.equals(c.username))
							{
								buyer_IP = c.cli_IP;
								buyer_port = c.cli_port;
							}
						}
						System.out.println("Reached till after the for loop");
						//When the seller is offline
						if((buyer_IP.toString().equals(IPAddress.toString())) && (buyer_port == port))
						{
							System.out.println("This is an offline buy");
							int i;
							int code =0;
							String itemName=null;
							int buyNowPrice=0;
							String itemOwner =null;
							for(i=0;i<itemList.size();i++)
							{
								Item I = itemList.get(i);
								if(I.item_code == item_Code)
								{
									code = I.item_code;
									itemName=I.name;
									buyNowPrice=I.buynow;
									itemOwner = I.owner;
									break;
									
								}
								
							}
							
							if(i == itemList.size())
							{
								message = "[Error: "+item_Code+" not found]";
								sendUDPPacket(message,IPAddress,port,currentuser);
								
							}
							else
							{
								itemList.remove(i);
								message ="[purchased "+code+" "+itemName+" "+buyNowPrice+" ]";
								System.out.println(message);
								sendUDPPacket(message,IPAddress,port,currentuser);
								System.out.println("Adding seller message to offline list");
								message ="Offline message :[sold "+code+" "+itemName+" ]";
								System.out.println("Adding the offline message");
								addOfflineMessage(itemOwner,message);
								sendACK(IPAddress,port);
							}
						}
						//Normal operation when the seller is online
						else
						{
						int i;
						int code =0;
						String itemName=null;
						int buyNowPrice=0;
						for(i=0;i<itemList.size();i++)
						{
							Item I = itemList.get(i);
							if(I.item_code == item_Code)
							{
								code = I.item_code;
								itemName=I.name;
								buyNowPrice=I.buynow;
								break;
								
							}
							
						}
						
						if(i == itemList.size())
						{
							message = "[Error: "+item_Code+" not found]";
							sendUDPPacket(message,IPAddress,port,currentuser);
							
						}
						else
						{
							itemList.remove(i);
							message ="purchased "+code+" "+itemName+" "+buyNowPrice;
							System.out.println(message);
							sendUDPPacket(message,buyer_IP,buyer_port,buyerName);
							System.out.println("Sending to seller");
							message ="sold "+code+" "+itemName;
							sendUDPPacket(message,IPAddress,port,currentuser);
						}
						
						}
						
						
						
					}
			
								
				}//end of while loop
				
			}//end of receiver function
	
		});//end of runnable
		
		tReceiverthread.start();
		System.out.println("Thread started");
	}//end of startReceiver
		
	
	

	
	public static void main(String[] args) throws Exception
	{
		// TODO Auto-generated method stub
		
		String[] split_commands = new String[3];
			
		clientList.clear();
		itemList.clear();
		offline_List.clear();
		
		BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System. in) );
		boolean value = false;
		boolean flag = true;
		
		
		System.out.println("Please enter the command\n");
		while(!value)
		{
			String command = inFromUser.readLine();
			split_commands = command.split(" ");
			if(split_commands.length == 3)
			{
				if((Integer.parseInt(split_commands[2]) < 1024) || (Integer.parseInt(split_commands[2]) > 65535))
				{
					System.out.println("[Error : port number out of range ]");
					
				}
				else
				{
					if(!split_commands[1].equals("-s"))
					{
						System.out.println("[Error : not a server command ]");
					}
					else
					{
					value = true;
					}
				}
			}
			else
			{
				System.out.println("[Error : 2 arguments required ]");
				
			}
		}
		
		
		serverSocket = new DatagramSocket(Integer.parseInt(split_commands[2]));
		System.out.println("Server has been started\n");
		byte[] sendData = new byte[8192];
		
		new UDPServer().startReceiving(); 	}//main
}//class
 

 

 

UDPClient.java

package bidding;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.*;

public class UDPClient extends Thread{

	
	/****/
	
	/*** @param args */
	
	public static boolean ACK;
	
	public static ArrayList<client> clientList = new ArrayList<client>();
	public static DatagramSocket clientSocket;
	public static boolean OFFLINE_BUY=false;
	public static boolean REGISTER = false;
	public static boolean DEREGISTER = false;
	public static boolean ACTIVE = false;
	public static String direct_buy;
	public static String sellerName;
	public static String[] split_command1 = new String[20];
	public static int port;
	public static InetAddress host;
	public static String name;
	
	public static void sendACK(InetAddress IP,int port)
	{
		System.out.println("Sending ack for register");
		byte[] data = new byte[4096];
		data = "acknowledgement".getBytes();
		DatagramPacket sendPacket = new DatagramPacket(data,data.length, IP, port);
		try {
			clientSocket.send(sendPacket);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
		
		
		
	}
	
	
	public static void sendUDPPacket(String info , InetAddress IP , int port)
	{
		
		byte[] sendData = new byte[4096];
		sendData=info.getBytes();
		//The code for waiting for time out and 5 attempts is commented because it makes the
		 //code go into an infinite loop
		
				/*int attempt_no = 0;
				ACK = false;
				while ((!ACK && attempt_no < 5) ) 
				{		*/
					DatagramPacket sendPacket = new DatagramPacket(sendData,sendData.length, IP, port);

					try {
						clientSocket.send(sendPacket);
						/*try {
							Thread.sleep(500);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							//e.printStackTrace();
						}*/
						
					} catch (IOException e) {
						
					}
					
					
			/*}
					if(!ACK)
						System.out.println("[ Host unavailable ]");*/
	}
					
					
	//Used to broadcast information about all clients to all the clients
	public static void updateTables(String[] InfoList) throws UnknownHostException
	{
		clientList.clear();
		String[] split_client_info = new String[3];
		
		for(int i=0;i<InfoList.length; i++)
		{
			
			split_client_info = InfoList[i].trim().split(" ");
			String username= split_client_info[0].trim();
			InetAddress IP= InetAddress.getByName(split_client_info[1].substring(1));
			int port= Integer.parseInt(split_client_info[2].trim());
			client c = new client(username,IP,port);
			clientList.add(c);
		}
	
		System.out.println("sobs>[Client table updated]");
		System.out.print("sobs>");
	}
	
	
	//Receiver thread
	public void startReceiving()
	{
		Thread tReceiverthread = new Thread(new Runnable()
		{
			@Override
			public void run() 
			{
				try 
				{
					UDPReceiver();

				} 
				catch (Exception e) 
				{
					// e.printStackTrace();
				}
			}
	

			@SuppressWarnings("unchecked")
			public void UDPReceiver() throws IOException
			{
				while(true)
				{
			
					byte[] receiveData = new byte[8192];
					DatagramPacket receivePacket =new DatagramPacket(receiveData,receiveData.length);
					try 
					{
						clientSocket.receive(receivePacket);
					}
					
					catch (IOException e) 
					{
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					if(!ACTIVE)
						continue;
					InetAddress receiverIP = receivePacket.getAddress();
					int receiver_port = receivePacket.getPort();
					String reply =new String(receivePacket.getData());
				
				//	Checking if the received packet is an ack
					if(reply.trim().equalsIgnoreCase("acknowledgement"))
					{
						
						ACK = true;
						if(OFFLINE_BUY)
						{
							System.out.println("sobs> [ "+sellerName+" is offline. Request has been forwarded to the server ]");
							System.out.print("sobs>");
								OFFLINE_BUY = false;
						}
						else if(REGISTER)
						{
							System.out.println("sobs> [Welcome "+name+", you have successfully signed in.] ");
							System.out.print("sobs>");
							REGISTER =false;
						}
						else if(DEREGISTER)
						{
							System.out.println("sobs> [You have successfully signed out. Bye!]");
							System.out.print("sobs>");
							DEREGISTER = false;
						}
					}
					
					//broadcasting to all clients
					
					else if(reply.trim().equals("broadcast"))
					{
						String[] clientInfoList = new String[1000];
												
						while(!reply.trim().equals("sent"))
						{
							byte[] receiveData1 = new byte[4096];
							DatagramPacket receivePacket1 =new DatagramPacket(receiveData1,receiveData1.length);
							clientSocket.receive(receivePacket1);
							String Reply = new String(receivePacket1.getData());
							if(Reply.trim().equals("sent"))
								break;
							Reply = Reply.replace("[", "");
							Reply = Reply.replace("]", "");
							clientInfoList = Reply.split(",");
														
						}
						updateTables(clientInfoList);
						
					}
					//buy and offline buy
					else if(reply.contains("buy"))
					{
						
						int i;
						String[] split_buy = new String[3];
						split_buy = reply.split(" ");
						String buyerName=null;
						for(i =0;i<clientList.size();i++)
						{
							client c = clientList.get(i);
							if(c.cli_IP.toString().equals(receiverIP.toString()) && c.cli_port == receiver_port)
							{
								buyerName = c.username;
								System.out.println("sobs>[ "+buyerName+" wants to buy your item "+split_buy[2].trim()+" ]");
								System.out.print("sobs>");
								direct_buy = "direct "+split_buy[2].trim()+" "+buyerName;
								sendUDPPacket(direct_buy,host,port);
								break;
							}
						}
						
												
					}
					
					else if(split_command1[0].equals("deregister"))
					{
						
							
					}
					else if(split_command1[0].equals("register"))
					{
						//Receiving offline messages					
						while(!reply.trim().equals("done"))
						{
							
							System.out.println("sobs> [ " +reply+" ]");
							byte[] receiveData2 = new byte[8192];
							DatagramPacket receivePacket2 =new DatagramPacket(receiveData2,receiveData2.length);
							try {
								clientSocket.receive(receivePacket2);
								
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							reply =new String(receivePacket2.getData());
						}//end of while for receiving offline messages
						System.out.print("sobs>");
					}//end of register
			
					else if(split_command1[0].trim().equals("info"))
					{
						
			
						if(split_command1.length == 1)
						{

							//Receiving info for all items
							while(!reply.trim().equals("done"))
							{
								
								System.out.println("sobs>" +reply);
								
								byte[] receiveData2 = new byte[8192];
								DatagramPacket receivePacket2 =new DatagramPacket(receiveData2,receiveData2.length);
								try {
									clientSocket.receive(receivePacket2);
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								reply =new String(receivePacket2.getData());
						
							}
							System.out.print("sobs>");
						}
						else
						{
							
							System.out.println("sobs>" +reply);
							System.out.print("sobs>");
					
						}
			
					}//end of info
					else 
					{
						
						System.out.println("sobs>" +reply);
						System.out.print("sobs>");
					}
					
					
			
				}//end of while loop
				
			}//end of receiver function
	
		});//end of runnable
		
		tReceiverthread.start();
		//System.out.println("Thread started");
	}//end of startReceiver
		
	
	public static void main(String[] args) throws Exception {
		
		new UDPClient().startProgram();
		// TODO Auto-generated method stub
	}
	
	public void startProgram() throws Exception
	{
		
		String[] split_commands = new String[10];
		String command = "";
		
		
		Pattern pattern = Pattern.compile("^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
		                "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
		                "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\." +
		                "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$");
		BufferedReader inFromUser =	new BufferedReader(new InputStreamReader(System. in) );
		clientSocket = new DatagramSocket();
		boolean value = false;
		startReceiving();
		System.out.println("Please enter your command\n");
				
				//Validating the first input
				
		while(!value)
		{
		    command = inFromUser.readLine();
			split_commands = command.split(" ");
			if (split_commands[0].equals("sobs"))
			{
				if(split_commands.length == 4)
				{
					if((Integer.parseInt(split_commands[3]) < 1024) || (Integer.parseInt(split_commands[3]) > 65535))
					{
						System.out.println("[ Error : port number out of range ]");
							
					}
					else
					{
						if(split_commands[1].equals("-c"))
						{
							port = Integer.parseInt(split_commands[3]);
							Matcher match = pattern.matcher(split_commands[2]);
							if (match.matches())
							{
								host = InetAddress.getByName(split_commands[2]);
								value = true;
							}
							else
							{
								System.out.println("[Error : Invalid IP ]");
								
							}
						}
						else
						{
							System.out.println("[Error : No a client command ]");
						}
					}
				}
				else
			    {
				System.out.println("[ Error : arguments ]");
					
			    }
			}
			else
			{
				System.out.println("[ Error : Incorrect command ]");
						
			}
				
		}
				
				
				
				
		System.out.print("sobs>");
				
		while(true)
		{
					
			command = inFromUser.readLine();
			split_command1 = command.split(" ");
			if(split_command1[0].equals("buy"))
			{
				if(!ACTIVE)
				{
					System.out.println("sobs>[Error : Not registered]");
					System.out.print("sobs>");
				}
				else if(split_command1.length != 3)
				{
					System.out.println("sobs> [Error : incorrect number of arguments ]");
					System.out.print("sobs>");
				}
				else
				{
					sellerName = split_command1[1];
					InetAddress seller_IP = null;
					int seller_port = 0;
					int i;
					for(i=0;i<clientList.size();i++)
					{
						client c = clientList.get(i);
						if(sellerName.trim().equals(c.username))
						{
							seller_IP = c.cli_IP;
							seller_port = c.cli_port;
							break;
								
								
						}
					}
					if(i == clientList.size())
					{
						OFFLINE_BUY = true;
						direct_buy = "direct "+split_command1[2]+" "+name;
						sendUDPPacket(direct_buy,host,port);
					}
						
					else
					{
						sendUDPPacket(command,seller_IP,seller_port);
					}
						
				}
			}
			else if(split_command1[0].equals("register"))
			{
				if(split_command1.length != 2)
				{
					System.out.println("sobs> [Error : incorrect number of arguments ]");
					System.out.print("sobs>");
				}
				else
				{
					name = split_command1[1];
					REGISTER = true;
					ACTIVE = true;
					sendUDPPacket(command,host,port);
				}
					
			}
			else if(split_command1[0].equals("deregister"))
			{
				
				if(!ACTIVE)
				{
					System.out.println("sobs>[Error : Not registered]");
					System.out.print("sobs>");
				}
				else if(split_command1.length != 1)
				{
					System.out.println("sobs> [Error : incorrect number of arguments ]");
					System.out.print("sobs>");
				}
				else
				{
					DEREGISTER = true;
					ACTIVE = false;
					sendUDPPacket(command,host,port);
				}
					
			}
			else if(split_command1[0].equalsIgnoreCase("sell"))
			{
				if(!ACTIVE)
				{
					System.out.println("sobs> [Error : Not registered]");
					System.out.print("sobs>");
				}
				else if(split_command1.length != 6)
				{
					System.out.println("sobs> [Error : incorrect number of arguments");
					System.out.print("sobs>");
				}
						
				else
				{
					sendUDPPacket(command,host,port);
				}
			}
			else if(split_command1[0].equalsIgnoreCase("bid"))
			{
				if(!ACTIVE)
				{
					System.out.println("sobs>[Error : Not registered]");
					System.out.print("sobs>");
				}
				else if(split_command1.length != 3)
				{
					System.out.println("sobs> [Error : incorrect number of arguments ]");
					System.out.print("sobs>");
				}
						
						
				else
				{
					sendUDPPacket(command,host,port);
				}
			}
			else if(split_command1[0].equalsIgnoreCase("info"))
			{
				if(!ACTIVE)
				{
					System.out.println("sobs>[Error : Not registered]");
					System.out.print("sobs>");
				}
				else if(split_command1.length > 3)
				{
					System.out.println("sobs> [Error : incorrect number of arguments ]");
					System.out.print("sobs>");
				}
						
						
				else
				{
					sendUDPPacket(command,host,port);
				}
			}
			else
			{
				System.out.println("sobs>[Error : Unknown command ]");
				System.out.print("sobs>");
			}
				
		}
				
				
				//clientSocket.close();
	}


}


 

 

 

Classes used :

UDPServer :

This class performs all the operations of the server.

There are two threads running : One is the main thread and the other one is just for receiving data.

UDPClient:

This class performs all the operations of the client.

There are two threads running:One is the main thread and the other one is just for receiving data.

Item:

It contains all the required details of an Item.

item_code

name

owner

translimit

startbid

buynow

description

current_bid

transaction_count

buyername

 

client:

It contains the necessary details of the client.

username

cli_IP

cli_port

offline_user:

It contains the details of an offline message.

name

message

 

Features Implemented :

The start commands on the server as well as the client :

sobs  -s port_no

sobs  -c IP port_no

Errors thrown :

Port number out of range.

Invalid IP.

Less or more number of arguments.

Anything other than –s on the server.

Anything other than –c on the client.

Client commands :

register and deregister

All the requested features have been implemented.

When the commands are entered the server sends acknowledgement and appropriate messages are printed on the client window.

The client information tables are broadcasted and updated.

No information can be sent or received after deregister.

Sends offline message if any are present.

sell

Results printed on the window :

[Error :arguments]

[<item-name> added with number <item-code>]

The description for the item needs to be entered separated by underscores. Example can be seen in the test cases mentioned after this section.

info

[Error : Empty]

[Error : Item not found]

[Details of a particular item]

Details of all the items.

bid

[Error : arguments]

[Error:owner]

[Error:duplicate bid]

[Error:item not found]

[<item number> <item name> <current bid>]

Sold [<item number> <item name> <current bid>]

Purchased [<item number> <item name> <current bid>]

Adds to offline messages if the client is not online anymore.

buy

Implemented like the diagram shown.

Customer to seller, seller to the server and then sold and purchased indications to both.

offline-buy

Customer to server, purchased and seller offline indication to customer and offline message saved for the seller.

Feature not implemented:

I could not successful ly implement the sending of acknowledgement from client to server and server to client everytime it receives a packet . If the acknowledgement is not received even after 5 times the message is stored in the offline messages for that user. Everytime I added this portion of my code the program went into an infinite loop on the register command itself. I could not successfully debug it. I have commented that portion of the code in my program.

Testing

The program has been tested with one server and three client running on the clic lab machine.

Makefile contents :

JFLAGS =  -g

JC = javac

JCLASSPATH = -cp .:../../bin

.SUFFIXES: .java .class

 

.java.class:

        $(JC) $(JFLAGS) $(JCLASSPATH) $*.java

 

CLASSES = \

        Item.java \

        client.java \

        offline_user.java

 

SOME =  UDPClient.java \

        UDPServer.java

default:classes

 

classes :$(CLASSES:.java=.class)

main :$(SOME:.java=.class)

 

clean:

        $(RM) *.class

 

 

SubmissionFolder/FinalUDPServerClient/src/bidding : make classes (builds the dependency classes)

SubmissionFolder/FinalUDPServerClient/src/bidding : make main (builds the Server and Client classes)

To run the code you need to come back one folder to src and execute java bidding.UDPServer(for server) , java bididng.UDPClient(for client)

 

Test Cases:

Server:

sobs -s 3567869

[Error : port number out of range ]

sobs -s

[Error : 2 arguments required ]

sobs -s 1236

Server has been started

 

Client 1:

sobs -c 767838 1234

[Error : Invalid IP ]

sobs -c 127.0.0.1 1236

sobs>register nandita

sobs> [Welcome nandita, you have successfully signed in.]

sobs>sobs>sobs>[Client table updated]

sobs>info

sobs>[Error : empty]

sobs>sell pen 3 200 600 fountain_pen

sobs>[pen added with number 1]

sobs>sell pencil 2 500 800 new_pencil

sobs>[pencil added with number 2]

sobs>sobs>[Client table updated]

sobs>bid 1 100

 

sobs>[ Error : owner ]

sobs>sobs>[Client table updated]

sobs>sobs>[ sold :1 pen 600 ]

sobs>sobs>[ geetha wants to buy your item 2 ]

sobs>sobs>sold 2 pencil

sobs>sobs>[Client table updated]

sobs>sobs>[Client table updated]

sobs>

Client 2:

sobs>register geetha

sobs> [Welcome geetha, you have successfully signed in.]

sobs>sobs>sobs>[Client table updated]

sobs>info

sobs>1 pen nandita 200 600 fountain_pen

sobs>2 pencil nandita 500 800 new_pencil

sobs>bid 1 300

sobs>1 pen 500

sobs>bid 1 200

sobs>[ Error : duplicate bid ]

sobs>sobs>[Client table updated]

sobs>buy nandita 2

sobs>purchased 2 pencil 800

sobs>sobs>[Client table updated]

sobs>info

sobs>3 pan satish 400 600 frying_pan

sobs>buy satish 3

sobs>[purchased 3 pan 600 ]

sobs> [ satish is offline. Request has been forwarded to the server ]

sobs>sobs>[Client table updated]

sobs>

 

Client 3:

Please enter your command

 

sobs -c 127.0.0.1 1236

sobs>info

sobs>[Error : Not registered]

sobs>register satish

sobs> [Welcome satish, you have successfully signed in.]

sobs>sobs>sobs>[Client table updated]

sobs>info

sobs>1 pen nandita 500 600 fountain_pen

sobs>2 pencil nandita 500 800 new_pencil

sobs>bid 1 100

sobs>[ purchased :1 pen 600 ]

sobs>sell pan 2 400 600 frying_pan

sobs>[pan added with number 3]

sobs>deregister

register satish

sobs> [Welcome satish, you have successfully signed in.]

sobs>sobs> [ Offline message :[sold 3 pan ]

sobs>sobs>[Client table updated]

sobs>

 

 

 

 

 

分享到:
评论

相关推荐

    reactor-netty, TCP/HTTP/UDP 客户机/服务器,带有联网的反应器.zip

    reactor-netty, TCP/HTTP/UDP 客户机/服务器,带有联网的反应器 反应器联网 http://projectreactor.io/docs/netty/release/api/在软件许可证 2.0许可,,,。

    UDP-echo-client-server.rar_Echo Echo_java udp_java udp echo_udp

    在这个“UDP echo client server”项目中,我们有两个核心文件:UDPClient.java 和 UDPEchoServer.java。这两个文件分别实现了UDP协议中的客户端和服务端功能,用于演示UDP数据包的发送和接收,也就是所谓的回显服务...

    p2p网络聊天室-----c/s模式

    在IT行业中,P2P(Peer-to-Peer)和C/S(Client/Server)模式是两种常见的网络架构,它们在构建分布式系统,尤其是聊天室应用时有着不同的应用场景和优势。在此,我们将深入探讨这两种模式以及如何实现一个具备私聊...

    Java-network-programming-server.zip_java programming_java server

    这就是经典的C/S(Client/Server)模型。 在"服务器.jar"中,很可能包含了一个Java编写的网络服务器程序。这个程序可能实现了TCP或UDP协议,处理来自客户端的连接请求,并进行数据交换。TCP提供的是面向连接的、...

    UDPServer和UDPClient

    在实际编程中,UDPServer和UDPClient的实现通常涉及网络编程API,如在Java中使用`DatagramSocket`类,或者在C++中使用`socket`函数。开发时需注意以下几点: 1. 数据包大小限制:UDP数据包最大为65535字节,超过这个...

    java-udp.rar_UDP Java_UDP java socket_java socket _java socket

    这个教程将深入讲解如何使用Java进行UDP网络通讯,并通过两个核心文件`UDPServer.java`和`UDPClient.java`的实例来阐述关键概念。 首先,UDP是一种无连接的协议,它不建立连接,而是直接发送数据包。每个数据包都...

    java-udp-qq聊天源码,p2p通信完全实现

    java-udp-qq聊天源码,p2p通信完全实现 UDP打洞实现了子网间的穿透功能,首先在一台拥有公网IP服务器上运行server,在不同的两个子网PC上运行client,输入服务器IP,即可进行打洞,实现不同子网的通信。

    Java 在Client-Server 网络中的应用

    ### Java在Client-Server网络中的应用详解 #### 一、Java网络应用模型 随着Java语言的广泛应用及其与互联网的高度融合,Java已经成为构建现代信息系统的重要工具之一。Java的特点,如跨平台性、面向对象的设计理念...

    UDP聊天程序_rowqfw_网络编程_udp进行c/s编程_

    C/S架构是网络通信中常见的模型,其中客户端(Client)发送请求到服务器(Server),服务器处理请求并返回响应。在UDP聊天程序中,客户端将发送包含消息的数据包到服务器,服务器接收到这些数据包后,再广播回所有的...

    UDP-Server-master.zip_java udp server

    public class UDPServer { public static void main(String[] args) throws Exception { int port = 12345; // 设置监听端口 DatagramSocket serverSocket = new DatagramSocket(port); byte[] receiveData = ...

    udp.txt

    在给定的代码中,`UDPServer`类实现了UDP服务器的基本功能。首先,通过`new DatagramSocket(5050)`创建了一个监听5050端口的`DatagramSocket`对象。然后,定义了一个字节数组`recvBuf`用于接收数据,并通过`...

    安卓网站交互JSONxmlWebserviceUPnP相关-AndroidUDP组播的例子包含Android组播Server和Client端发送端和接收端.zip

    中的"JavaApk源码说明.txt"可能包含了关于源码的详细解释和使用指南,"下载更多打包源码~.url"可能是一个链接,指向更多相关的Android开发资源,"UDP_Multicast_Client"和"UDP_Multicast_Server"则是实际的Android...

    java实现基于netty 的udp字节数据接收服务

    然而,当使用Netty时,我们可以通过`io.netty.channel.udps.UdpServer`和`io.netty.channel.udps.UdpChannel`来构建更复杂的网络应用。下面是一个简单的Netty UDP服务端实现的概述: 1. **创建Bootstrap**: 首先,...

    TcpUdpServerClient:Java中的TCPUDP ServerClient平台

    UDPServer.java:UDP服务器的类对象 TCPClient.java:TCP客户端的类对象 UDPClient.java:UDP客户端的类对象 GUI类 Server.java:服务器的小程序文件,支持TCP和UDP; Client.java:服务器的小程序文件,TCP 和 UDP...

    TCP-server-and-client.rar_java Tcp _java tcp server_tcp server_t

    本项目“TCP-server-and-client.rar”提供了一个基于Java实现的TCP服务器和客户端的简单示例,旨在帮助初学者理解TCP通信的基本原理和编程实践。 首先,我们要了解TCP的主要特性:它是一种面向连接的、可靠的、基于...

    Java-Socket-data-transfer:使用Java Socket做一些基本的数据传输(TCP&UDP)

    string(UDP) 接收反向的input_string ### UML图(似乎不支持) Client-&gt;Server: req_code (TCP)Note right of Server: Check the req_codeServer-&gt;Client: UDP port number(UDP)Client-&gt;Server:input_string(UDP)...

    TCP加UDP的server+client大全

    本资源"TCP加UDP的server+client大全"提供了一套完整的TCP服务器和客户端以及UDP服务器和客户端的实现,帮助开发者更好地理解和运用这两种协议。 TCP是一种面向连接的、可靠的协议。它通过建立三次握手来确保连接的...

    ping:在Java中Linux中执行ping的服务器-客户端实现

    如果从终端运行,请确保目录并使用以下命令对其进行编译:服务器编译-&gt; javac UDP_Server.java Server_Receive.java NextGaussian.java服务器运行-&gt; java UDP_Server'port'//输入要在其上运行的端口您想打开不带...

    TCP-UDP.rar_TCP/UDP优化_java tcp udp

    本篇文章将深入探讨TCP与UDP的差异、优化策略以及在Java中如何实现TCP和UDP通信。 TCP是一种面向连接的、可靠的协议,它确保数据的正确顺序传输和无丢失性。TCP通过三次握手建立连接,确保双方都能正常通信。在数据...

Global site tag (gtag.js) - Google Analytics