//server
package tenthChapter; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; public class ChatServer { /** * read info from client * @param * @return * throws Exception */ public static void main(String[] args) { // TODO Auto-generated method stub ServerSocket server = null; Socket socket = null; BufferedReader inClient = null; try{ //create server socket with assignable port server = new ServerSocket(7777); //monitor port, wait for client request socket = server.accept(); //start thread of server sender, wait for send new ServerSender(socket).start(); //get server socket input stream inClient = new BufferedReader(new InputStreamReader( socket.getInputStream())); //receive info as long as client said anything while(true) { String str = inClient.readLine(); System.out.println("Client say: " + str); } } catch(IOException e) { e.printStackTrace(); } finally{ //close all try{ inClient.close(); } catch(IOException e) { e.printStackTrace(); } try{ socket.close(); } catch(IOException e) { e.printStackTrace(); } try{ server.close(); } catch(IOException e) { e.printStackTrace(); } } } } //send information to client class ServerSender extends Thread { Socket s; BufferedWriter outClient; BufferedReader sysIn; public ServerSender(Socket s) { //get servers socket this.s = s; try{ //initialize //get server socket output stream outClient = new BufferedWriter(new OutputStreamWriter( s.getOutputStream())); //get system.in stream sysIn = new BufferedReader(new InputStreamReader(System.in)); } catch(IOException e) { e.printStackTrace(); } } public void run() { try{ //send info to client as long as server said anything while(true) { //get contents and send to client String str = sysIn.readLine();
//because data into buffer at first, then you must be flust stream//before send data to others. otherwise you send data while buffer //is fulloutClient.flush();}} catch(IOException e) {e.printStackTrace();} finally { //close alltry{sysIn.close();} catch(IOException e) {e.printStackTrace();}try{outClient.close();} catch(IOException e) {e.printStackTrace();}}}}outClient.write(str+"\n");
//Client
package tenthChapter; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; public class ChatClient { /** * Method Interpretation * @param * @return * throws Exception */ public static void main(String[] args) { // TODO Auto-generated method stub Socket socket = null; BufferedReader inServer = null; try{ //create a socket with assignable ip and port socket = new Socket("localhost", 7777); //get client socket input stream inServer = new BufferedReader(new InputStreamReader( socket.getInputStream())); //start client sender thread, ready for send new ClientSender(socket).start(); //receive info as long as server said anything while(true) { String str = inServer.readLine(); System.out.println("Server say: " + str); } } catch(IOException e) { e.printStackTrace(); } finally{ //close all try{ inServer.close(); } catch(IOException e) { e.printStackTrace(); } try{ socket.close(); } catch(IOException e) { e.printStackTrace(); } } } } //send information to servser class ClientSender extends Thread { Socket s; BufferedWriter outServer; BufferedReader sysIn; public ClientSender(Socket s) { this.s = s; try{ //initialize //get client socket output stream outServer = new BufferedWriter(new OutputStreamWriter( s.getOutputStream())); //get system.in stream sysIn = new BufferedReader(new InputStreamReader( System.in)); } catch(IOException e) { e.printStackTrace(); } } public void run() { try{ //send info to client as long as server said something while(true) { //get contents and send to server String str = sysIn.readLine(); outServer.write(str+"\n"); //must be flush buffer outServer.flush(); } } catch(IOException e) { e.printStackTrace(); } finally { //close all try{ sysIn.close(); } catch(IOException e) { e.printStackTrace(); } try{ outServer.close(); } catch(IOException e) { e.printStackTrace(); } } } }
//PrintScreen
//Notice:
/* watch red code, BufferedWriter.write(str + "\n") , why and "\n". It doesn't work in eclipse if you not. Please watch api:
* A newLine() method is provided, which uses the platform's own notion of line separator as defined by the system property line.separator.Not all *platforms use the newline character ('\n') to terminate lines. Calling this method to terminate each output line is therefore preferred to writing a *newline character directly.
*/
//suggestion:
// outClient.write(str+"\n"); -> outClient.write(str); outClient.newLine();
//use udp come true
package tenthChapter; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.util.Scanner; public class UDPServer { /** * Method Interpretation * @param * @return * throws Exception * @throws SocketException */ public static void main(String[] args) throws IOException { //create a datagram socket with assign port of receive DatagramSocket ds = new DatagramSocket(8999); byte[] b = new byte[1024]; DatagramPacket dp = new DatagramPacket(b, b.length); //start sender thread new SSender().start(); //receive info from client while(true) { ds.receive(dp); String str = new String(dp.getData(), 0, dp.getLength()); System.out.println("Client say: " + str); } } } //sender class SSender extends Thread { private DatagramSocket ds; private DatagramPacket dp; private byte[] b; public SSender() { try{ //create a datagram socket with assign port of destination ds = new DatagramSocket(9000); b = new byte[1024]; dp = new DatagramPacket(b, b.length, InetAddress.getLocalHost(), 8888); } catch(SocketException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } } public void run() { Scanner scanner = new Scanner(System.in); try{ while(true) { b = scanner.next().getBytes(); dp.setData(b); ds.send(dp); } } catch(IOException e) { e.printStackTrace(); } finally { ds.close(); } } }
package tenthChapter; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.util.Scanner; public class UDPClient { /** * Method Interpretation * @param * @return * throws Exception */ public static void main(String[] args) throws IOException{ DatagramSocket ds = new DatagramSocket(8888); byte[] b = new byte[1024]; DatagramPacket dp = new DatagramPacket(b, b.length); new CSender().start(); while(true) { ds.receive(dp); String str = new String(dp.getData(), 0, dp.getLength()); System.out.println("Server say: " + str); } } } //sender class CSender extends Thread { private DatagramSocket ds; private DatagramPacket dp; private byte[] b; public CSender() { try{ ds = new DatagramSocket(9001); b = new byte[1024]; dp = new DatagramPacket(b, b.length, InetAddress.getLocalHost(), 8999); } catch(SocketException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); } } public void run() { Scanner scanner = new Scanner(System.in); try{ while(true) { b = scanner.next().getBytes(); dp.setData(b); ds.send(dp); } } catch(IOException e) { e.printStackTrace(); } finally { ds.close(); } } }
//PrintScreen
//if you want to come true broadcast, you only record client's ip and port by list or others datastruct .
//or you want to come true group chat, you can watch my qt group chat, it's easy!
//but these are based on LAN