This site requires JavaScript, please enable it in your browser!
Greenfoot back
Roshan123
Roshan123 wrote ...

2022/3/14

Problem in importing Socket class

Roshan123 Roshan123

2022/3/14

#
Try removing "java.net." from line 18 & 54. It throws exception even if I have already imported "java.net" package in line 1
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){}
   }
} 
RcCookie RcCookie

2022/3/14

#
That's because your class itself is called "Socket", it will always reference that if not exactly specified with the fully qualified name.
Roshan123 Roshan123

2022/3/14

#
Oh, ok. Thanks for the answer. To be honest I thought its a problem in my editor
You need to login to post a reply.