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
Related
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
I've been studying the book Pro Java 7 NIO.2 to get a better understanding of the NIO package, and wanted to work on some networking related code to better my understanding of how netty works in the background. The over-all error makes sense, but why the error is being thrown is beyond my comprehension.
java.lang.ClassCastException: sun.nio.ch.ServerSocketChannelImpl cannot be cast to java.nio.channels.SocketChannel
The first thing that I did was make sure that none of my code was importing anything from the sun packaging, and that everything was in-fact using the java.nio package. Everything seems to check out.
This error is thrown when I attempt to connect a client to the server, but what really bothers me is the general fact that it's trying to type-cast to a ServerSocketChannel and not just a SocketChannel, which leads me to believe that the Server is confused.
I do apologise in advance for a wall of code down below, but as everyone always requests that I post a running example I plan to do just that. This is three class files small.
TcpProcessor.java
package net.ogserver.proto.tcp;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import net.ogserver.proto.connections.Connection;
public class TcpProcessor implements Runnable {
public static int tcpPort;
public void run() {
try (Selector selector = Selector.open();
ServerSocketChannel serverSocket = ServerSocketChannel.open()) {
if((serverSocket.isOpen()) && (selector.isOpen())) {
serverSocket.configureBlocking(false);
serverSocket.bind(new InetSocketAddress(tcpPort));
serverSocket.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("Server has started and is waiting for connections...");
while(!Thread.interrupted()) {
selector.select();
Iterator<SelectionKey> keys = selector.selectedKeys().iterator();
while(keys.hasNext()) {
SelectionKey key = (SelectionKey) keys.next();
keys.remove();
if(!key.isValid()) {
continue;
}
if(key.isAcceptable()) {
processIncomingConnection(key, selector);
} else if(key.isReadable()) {
//processIncomingData(key);
} else if(key.isWritable()) {
//pushOutgoingData(key);
}
}
}
} else {
System.err.println("There was an issue constructing the socket.");
}
} catch(IOException e) {
e.printStackTrace();
}
}
private void processIncomingConnection(SelectionKey selectionKey, Selector selector) throws IOException {
ServerSocketChannel serverSocket = (ServerSocketChannel)selectionKey.channel();
SocketChannel clientSocket = serverSocket.accept();
clientSocket.configureBlocking(false);
System.out.println("Incoming connection from " + clientSocket.getRemoteAddress());
selectionKey.attach(new Connection(selectionKey));
clientSocket.register(selector, SelectionKey.OP_READ);
}
}
Connection.java
package net.ogserver.proto.connections;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
public class Connection {
private SelectionKey selectionKey;
private SocketChannel clientSocket;
private ByteBuffer networkInputBuffer;
private ByteBuffer networkOutputBuffer;
public Connection(SelectionKey selectionKey) {
this.selectionKey = selectionKey;
this.clientSocket = (SocketChannel)selectionKey.channel();
this.networkInputBuffer = ByteBuffer.allocate(1024);
this.networkOutputBuffer = ByteBuffer.allocate(8192);
}
public SelectionKey getSelectionKey() {
return selectionKey;
}
public ByteBuffer getInputBuffer() {
return networkInputBuffer;
}
public ByteBuffer getOutputBuffer() {
return networkOutputBuffer;
}
public SocketChannel getChannel() {
return clientSocket;
}
}
Server.java
package net.ogserver.proto;
import net.ogserver.proto.tcp.TcpProcessor;
public class Server {
private Thread tcpProcessor;
public Server(int port) {
TcpProcessor.tcpPort = port;
tcpProcessor = new Thread(new TcpProcessor());
tcpProcessor.start();
}
public static void main(String[] args) {
new Server(5055);
}
}
There error occurs when TcpProcessor#processIncomingConnection is called, which invokes the creation of a new Connection instance. The line throwing this error is a direct quote from the book, and I've taken a look at a few other NIO servers and the line is exactly the same (Minus some naming) in most of them.
this.clientSocket = (SocketChannel)selectionKey.channel();
Any help would be greatly appreciated, full console output for those who want it:
Server has started and is waiting for connections...
Incoming connection from /127.0.0.1:53221
Exception in thread "Thread-0" java.lang.ClassCastException: sun.nio.ch.ServerSocketChannelImpl cannot be cast to java.nio.channels.SocketChannel
at net.ogserver.proto.connections.Connection.<init>(Connection.java:17)
at net.ogserver.proto.tcp.TcpProcessor.processIncomingConnection(TcpProcessor.java:60)
at net.ogserver.proto.tcp.TcpProcessor.run(TcpProcessor.java:37)
at java.lang.Thread.run(Thread.java:745)
I should probably add that the implementation of typecasting socketchannel form the selectionkey.channel() comes straight from the JavaDocs -- http://www.onjava.com/pub/a/onjava/2002/09/04/nio.html?page=2
You're passing the wrong SelectionKey to new Connection(...). You're passing the server socket's key. The key you should pass is the accepted socket's key, which is the result of socketChannel.register(), on the next line.
The sun.nio.ch.* classes appear to contain some implementations of interfaces in the java.nio.* package(s); the crossover to the different package occurs in the implementation classes you're using. No great mystery there.
By looking at the source for sun.nio.ch.ServerSocketChannelImpl, I see that it implements java.nio.channels.ServerSocketChannel, not java.nio.channels.SocketChannel. It's a channel implementation, not a socket implementation. Both the ServerSocketChannel and SocketChannel (in java.nio.channels) extend AbstractSelectableChannel, but they are siblings in the inheritance hierarchy, not ancestor/descendant.
Hope that helps.
I am new in Socket programming of java, i had written two files in Java named Server.java and Client.java as below:
Server.java
import java.io.*;
import java.net.*;
public class Server
{
static ServerSocket server = null;
static Socket socket = null;
static int userConnected=0;
static String msg = "In Server";
public static void main(String []args)throws Exception
{
int port = 1234;
server = new ServerSocket(port);
PrintStream output = null;
while(true)
{
socket=server.accept();
//Connection Arrived
userConnected++;
System.out.println("A new user arrived,\nNo. of user connected "+(userConnected));
}
}
}
Client.java
import java.net.*;
import java.io.*;
public class Client
{
static Socket socket = null;
public static void main(String[] args) throws Exception
{
socket = new Socket("localhost",1234);
}
}
When running Server class file on one system it will create Server on Port 1234 and when i run client class file it get successfully connected to Server on port 1234 and when i run another Client class file by another Console it also get connected to Server on port 1234,
What i want is to perform message passing between these two clients i.e. the message written in first client get shown in second client and vise-versa.
Can anyone please help me ??
http://www.tutorialspoint.com/java/java_networking.htm
I suggest you take a look at this. You can take a horse to the water, but cannot make it drink!
Check out ObjectOutputStream and ObjectInputStream in the standard Java API, you can then send Strings (and any other objects you want).
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.
I'm trying to make a simple HTML server that will read a request from my browser, parse the requested file from the request, then serve the appropriate HTML back to the browser. I need to be able to handle multiple requests, so I currently have a Server class acting as a parent of another runnable class RequestHandler. Each time a connection is made on the server, a new instance of the runnable class RequestHandler is run.
package server;
import java.io.IOException;
import java.net.ServerSocket;
public class Server {
public static void main(String[] args){
try{
ServerSocket serverSocket = new ServerSocket(8000);
for(;;){
Object block = new Object();
RequestHandler handler = new RequestHandler(block, serverSocket);
handler.start();
try{
synchronized(block){
System.out.println("Server thread paused...");
block.wait();
System.out.println("Server thread creating new RequestHandler...");
}
}catch(InterruptedException e){
System.out.println("Can't be interrupted!");
e.printStackTrace();
}
}
}catch(IOException e){
System.out.println("IOException!");
e.printStackTrace();
}
}
}
package server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class RequestHandler extends Thread {
Object block;
ServerSocket serverSocket;
BufferedReader socketReader;
PrintWriter socketWriter;
public RequestHandler(Object block, ServerSocket serverSocket){
this.block = block;
this.serverSocket = serverSocket;
}
#Override
public void run() {
try{
System.out.println("Waiting for request...");
Socket clientSocket = serverSocket.accept();
System.out.println("Connection made.");
synchronized(block){
System.out.print("Notifying server thread...");
block.notify();
System.out.println("...done");
}
socketReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
socketWriter = new PrintWriter(clientSocket.getOutputStream(), true);
String input;
while((input = socketReader.readLine()) != null){
System.out.println(input);
}
}catch(IOException e){
System.out.println("IOException!");
e.printStackTrace();
}
}
}
The problem I'm running into is that I'm not sure how to combine all the lines of the request so that I can parse the requested file. If it's just constantly waiting on request input, I'll never get to a point where I can parse the entirety of the request. How can I solve this problem?
your while loop will only break once the connection between the client and the server is closed. Since the client is waiting on the same connection for a response after sending the request the connection will remain open, so your readline() will block. In your while loop you have to check after every line whether you have reached the end of the request data. For GET requests, you have to look for a blank line following HTTP headers. For POST requests, you have to parse incoming headers looking for <Content-Length: N>. THen process the remaining headers looking for the blank line (just like in the GET case). Once you find the blank like, you have to read <N> bytes. At this point you know you've finished processing request data and should break out of the read loop.
Read the HTTP spec for details.
The first line gives you the request method as well as the requested path, the following lines are the request headers, the header block ends with a blank line.
That said, you are reinventing the wheel: you could use com.sun.net.httpserver.HttpServer