Ejemplo: crear una aplicación de chat utilizando el protocolo TCP o UDP
//Clientimportjava.io.*;importjava.net.*;publicclassGossipClientpublicstaticvoidmain(String[] args)throwsExceptionSocket sock =newSocket("127.0.0.1",3000);// reading from keyboard (keyRead object)BufferedReader keyRead =newBufferedReader(newInputStreamReader(System.in));// sending to client (pwrite object)OutputStream ostream = sock.getOutputStream();PrintWriter pwrite =newPrintWriter(ostream,true);// receiving from server ( receiveRead object)InputStream istream = sock.getInputStream();BufferedReader receiveRead =newBufferedReader(newInputStreamReader(istream));System.out.println("Start the chitchat, type and press Enter key");String receiveMessage, sendMessage;while(true)
sendMessage = keyRead.readLine();// keyboard reading
pwrite.println(sendMessage);// sending to server
pwrite.flush();// flush the dataif((receiveMessage = receiveRead.readLine())!=null)//receive from serverSystem.out.println(receiveMessage);// displaying at DOS prompt//Serverimportjava.io.*;importjava.net.*;publicclassGossipServerpublicstaticvoidmain(String[] args)throwsExceptionServerSocket sersock =newServerSocket(3000);System.out.println("Server ready for chatting");Socket sock = sersock.accept();// reading from keyboard (keyRead object)BufferedReader keyRead =newBufferedReader(newInputStreamReader(System.in));// sending to client (pwrite object)OutputStream ostream = sock.getOutputStream();PrintWriter pwrite =newPrintWriter(ostream,true);// receiving from server ( receiveRead object)InputStream istream = sock.getInputStream();BufferedReader receiveRead =newBufferedReader(newInputStreamReader(istream));String receiveMessage, sendMessage;while(true)if((receiveMessage = receiveRead.readLine())!=null)System.out.println(receiveMessage);
sendMessage = keyRead.readLine();
pwrite.println(sendMessage);
pwrite.flush();
Si para ti ha resultado de provecho nuestro post, te agradeceríamos que lo compartas con otros juniors así nos ayudas a dar difusión a nuestra información.
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)