Untitled
unknown
java
2 years ago
1.6 kB
1
Indexable
Never
package ie.gmit.dip; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class Server { public static void main(String[] args) { DataInputStream din = null; ServerSocket serverSocket = null; DataOutputStream dout = null; BufferedReader br = null; try { serverSocket = new ServerSocket(6666); System.out.println("Waiting for client to connect"); Socket socket = serverSocket.accept(); System.out.println("You are connected! You can now chat here via the console:"); din = new DataInputStream(socket.getInputStream()); OutputStream outputStream = socket.getOutputStream(); dout = new DataOutputStream(outputStream); br = new BufferedReader(new InputStreamReader(System.in)); String strFromClient = "", strToClient = ""; while (!strToClient.equals("\\q")) { strFromClient = din.readUTF(); System.out.println("Client says: " + strFromClient); strToClient = br.readLine(); dout.writeUTF(strToClient); dout.flush(); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (br != null) { br.close(); } if (din != null) { din.close(); } if (dout != null) { dout.close(); } if (serverSocket != null) { serverSocket.close(); System.out.println("Connection closed."); } } catch (IOException e) { e.printStackTrace(); } } } }