Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.*;
- import java.net.*;
- public class UDPClient
- {
- private GUIForClient gfc;
- public UDPClient(GUIForClient gfc)
- {
- this.gfc = gfc;
- }
- public static void main(String[] args) throws Exception
- {
- int cport = 29841;
- String host = "localhost";
- if (args.length < 1)
- {
- System.out.println("You are now connected to the host: " + host + " On port number: " + cport);
- }
- else{
- cport = Integer.valueOf(args[0]).intValue();
- System.out.println("You are now connected to the host: " + host + " On port number: " + cport);
- }
- InetAddress ia = InetAddress.getByName(host);
- SendThread send = new SendThread(ia, cport);
- send.start();
- ReceiveThread receive = new ReceiveThread(send.getSocket());
- receive.start();
- }
- }
- class SendThread extends Thread
- {
- private InetAddress serverIP;
- private DatagramSocket ds;
- private boolean stopThread = false;
- private int sport;
- public SendThread(InetAddress addr, int sport) throws SocketException
- {
- this.serverIP = addr;
- this.sport = sport;
- this.ds = new DatagramSocket();
- this.ds.connect(serverIP, sport);
- }
- public void halt()
- {
- this.stopThread = true;
- }
- public DatagramSocket getSocket()
- {
- return this.ds;
- }
- public void run()
- {
- try
- {
- byte[] b1 = new byte[1024];
- b1 = "".getBytes();
- DatagramPacket dp1 = new DatagramPacket(b1, b1.length, serverIP, sport);
- ds.send(dp1);
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- while (true)
- {
- if (stopThread)
- {
- return;
- }
- String messageFromClient = br.readLine();
- if (messageFromClient.equals("."))
- {
- break;
- }
- byte[] sentData = new byte[1024];
- sentData = messageFromClient.getBytes();
- DatagramPacket dp2 = new DatagramPacket(sentData, sentData.length, serverIP, sport);
- System.out.println("Please type your next message.");
- ds.send(dp2);
- Thread.yield();
- }
- }
- catch(IOException ioe)
- {
- System.err.println(ioe);
- }
- }
- }
- class ReceiveThread extends Thread
- {
- private DatagramSocket ds;
- private boolean stopThread = false;
- public ReceiveThread(DatagramSocket ds) throws SocketException
- {
- this.ds = ds;
- }
- private void halt()
- {
- this.stopThread = true;
- }
- public void run()
- {
- byte[] receivedData = new byte[1024];
- while (true)
- {
- if(stopThread)
- {
- return;
- }
- DatagramPacket dp3 = new DatagramPacket(receivedData, receivedData.length);
- System.out.println("You're in the client!");
- try
- {
- ds.receive(dp3);
- System.out.println("I will keep receiving packets...");
- String replyFromServer = new String(dp3.getData(), 0, dp3.getLength());
- System.out.println("UDPClient: Response from the server: \"" + replyFromServer + "\"\n");
- Thread.yield();
- }
- catch(IOException ioe)
- {
- System.err.println(ioe);
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement