udp - Where is the error // why doesn't it work? (Java Chat program) -
i wanted write udp java chat program can send , receive messages , person using program. figured out socket programming own (google search etc.), don't understand every single part. basic idea read random ip want chat string, converting ip , starting 2 threads, 1 sending messages port , 1 receiving messages @ port b (the threads used being both able send , recieve messages @ same time). every thread has it's own class. far, good. both classes have method run both in big try-catch block. @ 2 catch blocks, added several error messages, first "test123" , "test456" can understand happens when. when compiling code, can type in ip (i tried localhost testing). when type in message, should recieve message "chat partner sent: ", instead don't anything. both threads in infinite loop, when force program terminate (by pressing ctrl+c (i run .class via command)), error message "test123" before program terminates. questions are: why don't receive message , why program throw "test123" when force program terminate? errors? in advance helping. here's code:
import java.net.*; import java.util.scanner; public class chat { static inetaddress ip; static int sport=11111; static int rport=11112; public static void main(string[] args) throws exception{ system.out.println("zu welcher ip soll verbunden werden?");//"which ip want connect with?" scanner sc = new scanner(system.in); string ipraw=sc.next(); //type in ip address string ip=inetaddress.getbyname(ipraw); //converting string real ip address thread sender = new sender(); sender.start(); //start sending thread thread receiver = new receiver(); receiver.start(); //start receiving thread } } class sender extends thread{ public void run(){ byte[] senddata = new byte[1024]; scanner scantext = new scanner(system.in); try{ datagramsocket socket = new datagramsocket(); while(true){ string textsend = scantext.next(); senddata = textsend.getbytes(); datagrampacket out = new datagrampacket(senddata, senddata.length, chat.ip, chat.rport); socket.send(out); } } catch(exception e){ system.out.println("test123"); } } } class receiver extends thread{ public void run(){ byte[] receivedata = new byte[1024]; try{ datagramsocket socket = new datagramsocket(); while(true){ datagrampacket in = new datagrampacket(receivedata, receivedata.length, chat.ip, chat.sport); socket.receive(in); string message = new string(in.getdata()); system.out.println("chatpartner sagt: " + message);//"partner said <message>" } } catch(exception e){ system.out.println("test456"); } } }
the sender thread wating insert data on system.in (just type something). blocked here, on line: string textsend = scantext.next();
Comments
Post a Comment