Note that there are some explanatory texts on larger screens.

plurals
  1. POTCP socket connection
    text
    copied!<p>I'm new to the network communication and I'm trying to build client-server application.</p> <pre><code>protected void init(){ Server myServer = new Server(); Client myClient = new Client(); } </code></pre> <p>That's my Client class:</p> <pre><code>public class Client { public Client() { init(); } private void init() { Socket echoSocket = null; DataOutputStream os = null; DataInputStream is = null; DataInputStream stdIn = new DataInputStream(System.in); try { echoSocket = new Socket("localhost", 1234); os = new DataOutputStream(echoSocket.getOutputStream()); is = new DataInputStream(echoSocket.getInputStream()); os.writeInt(stdIn.readInt()); echoSocket.getOutputStream().close(); echoSocket.getInputStream().close(); echoSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } </code></pre> <p>And that's server:</p> <pre><code>public class Server { public Server() { init(); } private void init() { try { boolean run = true; ServerSocket ss = new ServerSocket(1234); Socket s = ss.accept(); DataInputStream dis = new DataInputStream(s.getInputStream()); System.out.println(dis.readInt()); s.getInputStream().close(); s.getOutputStream().close(); s.close(); } catch (IOException e) { e.printStackTrace(); } } } </code></pre> <p>First of all: Can I initialize client and server simply like i did? <code>new Server()</code> and <code>new Client()</code>?</p> <p>Question 2: Is it important what i initialize at first? client or server?</p> <p>Question 3: When i compile this code with client first initialized, i become <code>Connection refused: connect</code>. I know it means that there is no listening socket running on the port you are trying to connect to. That's why server must go first, i think. Is it so? can i fix it using <code>setSoTimeout</code> and how?</p> <p>Question 4: When i compile it with server and then client, output is nothing. And i think it has nothing to do with client, because if i try to print "1", for example, it doesn't work either. I think it just waits for the client and does nothing that goes after. How can i fix this? maybe <code>setSoTimeout</code> goes here too?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload