How is Socket working in Java? - java

i want to know the functionality of sockets in java. when i am creating some http-server i can use some ready to use sockets for secure and non-secure communication between two parties. but i never installed tomcat to my project, so my question is: how can java create a tcp / ip connection without a web-server? Can someone post me some link to clear this question?
In my case i used this to create a SSLSocket:
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import javax.net.ssl.SSLServerSocketFactory;
public class MainClass {
public static void main(String args[]) throws Exception {
SSLServerSocketFactory ssf = (SSLServerSocketFactory)SSLServerSocketFactory.getDefault();
ServerSocket ss = ssf.createServerSocket(5432);
while (true) {
Socket s = ss.accept();
PrintStream out = new PrintStream(s.getOutputStream());
out.println("Hi");
out.close();
s.close();
}
}
}
Thank u a lot,
Mira

Related

Socket ObjectOutputStream writeUTF() and ObjectInputStream readUTF() not working

I was trying to do a chat and I notice that readUTF() and writeUTF() did not work. readUTF() stays waiting when I already used writeUTF(). I made a simple test and does not work, what I am doing bad?
(I know that I could use Data Streams instead of Object Streams but in my chat I want to write objects and strings)
Server code:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(40001);
Socket s = server.accept();
ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream in = new ObjectInputStream(s.getInputStream());
System.out.println(in.readUTF());
out.writeUTF("E");
}
}
Client code:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class Client {
public static void main(String[] args) throws IOException {
Socket s = new Socket("localhost", 40001);
ObjectOutputStream out = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream in = new ObjectInputStream(s.getInputStream());
out.writeUTF("A");
System.out.println(in.readUTF());
}
}
I could use writeObject("A") and cast the String with readObject(), but I want to know why this way does not work.
You need to call flush() after writing using writeUTF. The reason that writeObject just seems to work is that writeObject will switch to a specific mode before it starts writing, and switch back after it is done. This switching back will automatically flush the buffered data (at least in Java 11). This is not the case for writeUTF, and an explicit call to flush() is needed.
ObjectOutputStream uses an internal buffer, so you should try out.flush() after writes if you want content to be available to read on the InputStream.
The javadoc for ObjectOutputStream includes:
callers may wish to flush the stream immediately to ensure that constructors for receiving ObjectInputStreams will not block when reading the header

Bind error even with setReuseAddress(true) [duplicate]

This question already has an answer here:
Address reuse not working on new Java Runtime Environment
(1 answer)
Closed 5 years ago.
Maybe I misunderstand the use of this code, but from what I understand, calling setReuseAddress(true) will allow the port to be used even if the computer still thinks it is in use.
Scenario: I have the below code. When it crashes it does not close the port, so it throws a bind error on next launch. I have used setReuseAddress(true) to try to force it to open the port, but it throws the same error. If this is the right code, how do I use it? If it's the wrong code, what will allow this behavior?
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
public class ServerPsswd {
public static void main(String[] args) throws IOException {
ServerSocket listener = new ServerSocket();
listener.setReuseAddress(true);
listener.bind(new InetSocketAddress(9090));
try {
while (true) {
Socket socket = listener.accept();
try {
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
out.println("tada!");
out.println("yays");
} finally {
socket.close();
}
}
}
finally {
listener.close();
}
}
}
https://docs.oracle.com/javase/7/docs/api/java/net/Socket.html#setReuseAddress(boolean)
It is to allow connections during the timeout period AFTER the current connection has been closed

ServerSocket on port 80 is it correct?

I read some materials about ServerSocket and tried to listen on port 80 and print for example InetAddress of website which I was opening in web browser but my program couldn't do this. My code:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Site implements Runnable {
private int port;
Site(int port){
this.port = port;
}
public void run() {
try {
ServerSocket server = new ServerSocket(port);
while(true){
Socket socket = server.accept();
System.out.println(socket.getInetAddress());
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String args[]){
Thread thread = new Thread(new Site(80));
thread.start();
}
}
When I run my program I am only one time in the while loop and the program doesn't print System.out.println(socket.getInetAddress()) and as the result when I open my web browser and visit http sites I don't see any output. Do you know what I am doing wrong? Do you know any other ways to print InetAddress for currently open website? Any materials will by appreciate.
I can't comment without proper reputation so forgive me for throwing everything out here:
you might already have something listening on port 80
you might be running on a version of linux that restricts non root process binding to ports above 1024
you might be blocked by a software firewall

java Connection reset error

I am quite a newbie to Java. Please excuse me if you find this as a very basic question.There are many answers available already in stack overflow about this and I went through almost all the possible helps i can get in Stack overflow and also in some other forums. Unfortunately none of them helped me.
I have client/server program in which the client send a string to server and server just attaches another string to the string sent by client and sends it back to the client.
Server program looks like this.
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class server {
public static void main(String[] args) {
try
{
ServerSocket server = new ServerSocket(7300);
Socket s = server.accept();
DataInputStream inp = new DataInputStream(s.getInputStream());
DataOutputStream out = new DataOutputStream(s.getOutputStream());
String str =inp.readUTF();
str = str+" buddy!";
out.writeUTF(str);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Client looks like This.
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.*;
public class client {
public static void main(String[] args) {
try
{
Socket s = new Socket("192.168.1.3",7300);
DataInputStream inp = new DataInputStream(s.getInputStream());
DataOutputStream out = new DataOutputStream(s.getOutputStream());
out.writeUTF("hi");
System.out.println(inp.readUTF());
Thread.sleep(2000);
out.writeUTF("hello");
System.out.println(inp.readUTF());
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Everything works fine while client writes "hi" and when client starts sending "hello" i am getting Connection reset error. I am not getting what mistake am i doing please help me in resolving this.
The output with the error i am getting looks like this.
hi buddy!
java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
at java.io.DataOutputStream.write(Unknown Source)
at java.io.DataOutputStream.writeUTF(Unknown Source)
at java.io.DataOutputStream.writeUTF(Unknown Source)
at sokry.client.main(client.java:18)
In your server example, readUTF is only called once on the DataInputStream, even though the client wrote to the DataOutputStream twice. Thus, simply adding
str = inp.readUTF();
str = str + " buddy!";
out.writeUTF(str);
to your server example, after the last out.writeUTF(str), will solve your problem.
do comment on following line of your client.java file and try.it will work
Thread.sleep(2000);
`//out.writeUTF("hello");;
//System.out.println(inp.readUTF());
because when you are sending "hi" from client to server and server gives reply then it finished it work and it stop connection but in client.java you sending another request to server but server is at rest.
you should start server until client finish it work..
hope it will wait

Sending keyboard presses to another computer?

I was wondering if i could get help making or finding a program that has the ability to send keyboard presses and receive them on another computer. I want to use this to play multiplayer flash-player games with friends across computers. I know there are some programs out there like "logmein" but both users cannot use the keyboard at the same time. (When i press a key the computer user cannot press a key at the same time because it wont respond.) I only know java and I am quite novice at it. Im guessing if i need to write it ill have to send the information through a port or onto a web-server. I would like to know your opinions and suggestions for this program, thanks guys.
Basically what you are looking for is a chatroom program? Have you tried looking into mIRC?
mIRC is a free internet relay chat. What exactly are the requirements for the program? Is there a certain size that it must be? Are these flash games that you and your friends are playing taking up your full computer screen?
Building a program would require a web-server(any computer with internet access would do), and you would have to open the ports on your network to allow the traffic to go through.
A basic server in java would look something like this:
Please note that after the first connection this "server" will close the connection.
import java.net.ServerSocket;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class Server
{
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static BufferedReader bufferedReader;
private static String inputLine;
public static void main(String[] args)
{
// Wait for client to connect on 63400
try
{
serverSocket = new ServerSocket(63400);
while(true){
clientSocket = serverSocket.accept();
// Create a reader
bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
// Get the client message
while((inputLine = bufferedReader.readLine()) != null)
{System.out.println(inputLine);}
serverSocket.close();
System.out.println("close");
}
}
catch(IOException e)
{
System.out.println(e);
}
}
}
And a client would almost be the same:
import java.net.Socket;
import java.io.PrintWriter;
public class client
{
private static Socket socket;
private static PrintWriter printWriter;
public static void main(String[] args)
{
try
{
//change "localhost" to the ip address that the client is on, and this number to the port
socket = new Socket("localhost",63400);
printWriter = new PrintWriter(socket.getOutputStream(),true);
printWriter.println("Hello Socket");
}
catch(Exception e)
{
System.out.println(e);
}
}
}
If I am not mistaken printWriter is a 16-bit operation, and in order to reduce lag, if you were just sending text then you might want to use printStream(). I believe that this might be a bit quicker.

Categories