sockets - Java UDP Connection -
i'm using netbeans ide trying make udp connection between client , server, it's simple program udpclient send string udpserver , server capitalize string , sends client.i made client side , server side in separated projects.
my class code client udpclient
:
package udpclient; import java.io.*; import java.net.*; public class udpclient { public static void main(string[] args) throws ioexception{ //get input user bufferedreader user_in = new bufferedreader( new inputstreamreader(system.in)); //create udp socket connection datagramsocket socket = new datagramsocket(); //creat buffers process data byte[] indata = new byte[1024]; byte[] outdata = new byte[1024]; //get ip destination wanted inetaddress ip = inetaddress.getbyname("localhost"); //read data user system.out.println("enter data send server: "); outdata = user_in.readline().getbytes(); /* * make pkts interaction */ //send pkts datagrampacket sendpkt = new datagrampacket(outdata, outdata.length, ip, 9876); socket.send(sendpkt); //receive pkts datagrampacket recievepkt = new datagrampacket(indata, indata.length); socket.receive(recievepkt); system.out.println("replay server: "+recievepkt.getdata()); } }
and server side class udpserver
:
package udpserver; import java.io.*; import java.net.*; public class udpserver { public static void main(string[] args) throws ioexception{ // todo code application logic //connection datagramsocket socket = new datagramsocket(); //pkt buffers byte[] inserver = new byte[1024]; byte[] outserver = new byte[1024]; //receive pkt datagrampacket rcvpkt = new datagrampacket(inserver,inserver.length); socket.receive(rcvpkt); //display receive system.out.println("packet received!"); //retrive pkt info send response same sender inetaddress ip = rcvpkt.getaddress(); int port = rcvpkt.getport(); //process data string temp = new string(rcvpkt.getdata()); temp = temp.touppercase(); outserver = temp.getbytes(); //send response packet sender datagrampacket sndpkt = new datagrampacket(outserver, outserver.length, ip, port); socket.send(sndpkt); } }
make in count program runs , outputs no error. server doesn't receive packet @ , didn't interact client. why happened ?
you haven't specified listening port in server server listen on random available port.
try on server side
datagramsocket socket = new datagramsocket(9876);
Comments
Post a Comment