Try removing "java.net." from line 18 & 54. It throws exception even if I have already imported "java.net" package in line 1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 | import java.net.*; import java.io.*; import java.util.*; public class Socket { public static void main(String[] args) throws Exception { new Thread( () -> runServer() ).start(); runClient(); } public static void runClient() throws Exception { try { String ip = "localhost" ; int port = 443 ; java.net.Socket s = new java.net.Socket(ip, port); System.out.println( "Type a message to Server" ); BufferedReader br; String fromS; Scanner sc; String toS= "" ; OutputStreamWriter os; PrintWriter out; while (!toS.equals( "exit" )) { br = new BufferedReader( new InputStreamReader(s.getInputStream())); fromS = br.readLine(); System.out.println( "Server: " +fromS); sc = new Scanner(System.in); toS = sc.nextLine(); os = new OutputStreamWriter(s.getOutputStream()); out = new PrintWriter(os); out.println(toS); os.flush(); } } catch (Exception e){} } public static void runServer() { try { System.out.println( "Server has started" ); ServerSocket ss = new ServerSocket( 443 ); System.out.println( "Server is waiting for the client" ); java.net.Socket s = ss.accept(); System.out.println( "Client Connected" ); System.out.println( "Type a message to Client" ); Scanner sc = new Scanner(System.in); String toC= "" ; OutputStreamWriter os; PrintWriter out; BufferedReader br; String fromC; while (!toC.equals( "exit" )) { toC = sc.nextLine(); os = new OutputStreamWriter(s.getOutputStream()); out = new PrintWriter(os); out.println(toC); os.flush(); br = new BufferedReader( new InputStreamReader(s.getInputStream())); fromC = br.readLine(); System.out.println( "Client: " +fromC); } } catch (Exception e){} } } |