I am trying to read a video file from local storgae by chunks and upload to a server. I have this code working in another java platform so i thought it would be quite simple.
When i try to open the File using
File f = new File(filePath);
fileIn = new FileInputStream(f);
it opens and i can read whatever i need from the file, further down in my code though i call
SocketFactory socketFactory = SSLSocketFactory.getDefault();
Socket socket = socketFactory.createSocket(url, 443);
_in = new InputStreamReader(socket.getInputStream());
_out = (OutputStream)socket.getOutputStream();
The socket connects fine but when I then come to read the FileInputStream after this bit of code I get stream closed exception.
Any ideas? I don't see anything in the log to show anything is failing but i can't read from the fileinputstream once i have conencted to the server??
Let me know if you need to know anything else to help.
This example worked for me:
public class MainClass {
public static void main(String[] args) {
String host = args[0];
int port = Integer.parseInt(args[1]);
try {
System.out.println("Locating socket factory for SSL...");
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
System.out.println("Creating secure socket to " + host + ":" + port);
SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
System.out.println("Enabling all available cipher suites...");
String[] suites = socket.getSupportedCipherSuites();
socket.setEnabledCipherSuites(suites);
System.out.println("Registering a handshake listener...");
socket.addHandshakeCompletedListener(new MyHandshakeListener());
System.out.println("Starting handshaking...");
socket.startHandshake();
System.out.println("Just connected to " + socket.getRemoteSocketAddress());
} catch (IOException e) {
e.printStackTrace();
}
}
}
class MyHandshakeListener implements HandshakeCompletedListener {
public void handshakeCompleted(HandshakeCompletedEvent e) {
System.out.println("Handshake succesful!");
System.out.println("Using cipher suite: " + e.getCipherSuite());
}
}
As snicolas said, socket.startHandshake() could fix your prob.
you didn't call socket.startHandshake();
Related
I'm working on a project that will require ea p2p server, but I haven't found any java-client php-server example code. I understand the concept of how udp hole punching works but I can't get anything to work in code.
What I've tried:
TheSocket.java
public class TheSocket {
public static String response = "hello";
public static String request;
public static String webServerAddress;
public static ServerSocket s;
protected static ServerSocket getServerSocket(int port)throws Exception{
return new ServerSocket(port);
}
public static void handleRequest(Socket s){
BufferedReader is;
PrintWriter os;
try{
webServerAddress = s.getInetAddress().toString();
is = new BufferedReader(new InputStreamReader(s.getInputStream()));
request = is.readLine();
System.out.println(request);
os = new PrintWriter(s.getOutputStream(), true);
os.println("HTTP/1.0 200");
os.println("Content-type: text/html");
os.println("Server-name: TheSocket");
os.println("Content-length: " + response.length());
os.println("");
os.println(response);
os.flush();
os.close();
s.close();
}catch(Exception e){
System.out.println("Failed to send response to client: " + e.getMessage());
}finally{
if(s != null){
try{
s.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
return;
}
}
Main.java
public class Main {
public static void main(String[] args)throws Exception{
TheSocket.s = TheSocket.getServerSocket(6789);
while(true){
Socket serverSocket = TheSocket.s.accept();
TheSocket.handleRequest(serverSocket);
}
}
PHP-CONNECT.php - to get the other users port, I manually connect and use the port shown on webpage.
<?php
echo $_SERVER['REMOTE_ADDR'].':'.$_SERVER['REMOTE_PORT'];
?>
The issue with the code above, is that it cant make it to the socket unless I port forward.
Comment if you have any questions!
I was facing a similar problem. And was trying to solve it in a similar way.
Some parts of your code look wrong to me.
Sockets in Java are made for TCP but the title says UDP. Therefore u should use DatagramSockets.
But then we come to the point where i stuck too. HTTP-Requests use tcp as well, so opening the port with HTTP might lead to a corrupt port, after tcp session was closed. (Just a guess)
public class Main {
public static void main(String[] args) {
try
{
String httpRequest = "GET /index.php HTTP/1.1\n" +
"Host: <PHP SERVER NAME HERE>";
InetAddress IPAddress = InetAddress.getByName(<PHP SERVER IP HERE>);
DatagramSocket clientSocket = new DatagramSocket();
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
String sentence = httpRequest;
sendData = sentence.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 80);
clientSocket.send(sendPacket);
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
clientSocket.receive(receivePacket);
String modifiedSentence = new String(receivePacket.getData());
System.out.println("FROM SERVER:" + modifiedSentence);
clientSocket.close();
}catch(Exception e){e.printStackTrace();}
}
}
The Code above theoretically sents a HTTP over UDP request. So that the displayed Port will be the UDP one. In my case i didnt get any response from the PHP Server and stuck at clientSocket.recieve(..) . I guess because the firewall of my webserver is blocking udp packets.
If the code works by anyone i would proceed like this:
save all accessing ips and ports to a DB and list them to the other client.
Write ur Data in DatagramPackets like above to the other client.
I hope this may help. If anyone can get it completly working i would also be interested in it :)
Hello stackoverflow community,
i am stuck at a problem regarding socket communication in Java.
Here is the sample code of my Server and Client class:
Server:
public class OTPServer {
static ServerSocket serverSocket;
final static int PORT = 4242;
static Socket clientConnection;
public static void main(String[] args) {
try {
serverSocket = new ServerSocket(PORT);
System.out.println("Socket initialized");
String serverMessage = "Hello, I am the Host";
ServerTool serverTool = new ServerTool();
while (true) {
clientConnection = serverSocket.accept();
if(clientConnection.isConnected()) {
System.out.println("Client connected");
}
BufferedReader clientInputReader = new BufferedReader(new InputStreamReader(clientConnection.getInputStream()));
DataOutputStream serverOutput = new DataOutputStream(clientConnection.getOutputStream());
System.out.println("Sending message to client: " + serverMessage);
serverOutput.writeBytes(serverTool.encodeMessage(serverMessage));
serverOutput.flush();
String clientMessage = clientInputReader.readLine();
System.out.println("Encoded answer from client: " + clientMessage);
String decodedMessage = serverTool.decodeMessage(clientMessage);
System.out.println("Decoded answer from client: " + decodedMessage);
serverOutput.close();
clientInputReader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Hello, I am the OTP Server!");
}
Here is the Client:
public class OTPClient {
static Socket clientSocket;
final static int PORT = 4242;
final static String HOST = "localhost";
public static void main(String[] args) {
System.out.println("I am the OTP Client!");
String serverMessage;
String clientResponse = "I am the Client";
OTPTool otpTool = new OTPTool();
try {
clientSocket = new Socket(HOST, PORT);
BufferedReader serverInput = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream());
System.out.println("Connection to Host established");
serverMessage = serverInput.readLine();
System.out.println("Encoded Message from Server: " + serverMessage);
String decodedMessage = otpTool.decodeMessage(serverMessage);
System.out.println("Decoded message from Server: " + decodedMessage);
System.out.println("Answering with own message: " + clientResponse);
outputStream.writeBytes(clientResponse);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Now where is my problem:
The connection establishes and the Server seems to send its message to the client and waits for a answer. The Client does not print the message he got from the Server.
As soon as i cancel the Server the client prints the message it gets from the server as well as the information, that the answer is send end exits with exit code 0 so it seems that this part is fine it just is stuck somehow.
I already tried to flush the outputStream as you see in the example code given.
Is there something obvious im missing?
I know, this is really basic stuff but its my first time using sockets for communication.
Thank you in advance!
Best Regards,
Ronny
Btw: i know that the server only connects to one client requesting a connection. Thats absolutely sufficient for my use.
It is getting stuck because serverInput.readLine(); blocks until either a line break or end of file is encountered. On the server side, you are not sending a line break, so the client blocks.
I have a socket programming code that goes..
Server Program
import java.net.*;
import java.io.*;
public class GreetingServer extends Thread
{
private static int port;
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(50000);
}
public void run()
{
while(true)
{
try
{
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataInputStream in =
new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
port=9000;
try
{
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
And the client side code that is...
import java.io.*;
import java.net.*;
public class GreetingClient
{
private static String serverName;
public static void main(String [] args)
{
String sName = "MyServerName";
int port = 9000;
try
{
System.out.println("Connecting to " + sName
+ " on port " + port);
Socket client = new Socket(sName, port);
System.out.println("Just connected to "
+ client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out =
new DataOutputStream(outToServer);
out.writeUTF("Hello from "
+ client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
}catch(IOException e)
{
}
}
}
The code compiles fine. But when i run the program, first the server and then the client, the server displays that
Waiting for client on port 9000...
Socket timed out!
and the client shows
Connecting to MyServerName on port 9000
What is wrong with the code?? I have tried increasing and decreasing the timeout values but it gives the same output.
What is wrong with the code?
There's nothing wrong with your code. You set a 50 second accept timeout, accept blocked for 50 seconds without a client trying to connect, so a SocketTimeoutException was thrown. Everything here is working as designed.
Of course it's possible that:
your accept timeout is too short
you don't want to abort your server just because of an accept timeout
you don't want an accept timeout at all.
All of these are design decisions that depend on your requirements.
It's also possible that you got the host name wrong in the client, but as you're ignoring exceptions in the client:
catch(IOException e)
{
}
there is no way you will ever find out. Never ignore IOExceptions.
Above code is perfectly working with sName in client as 'localhost', since I am running both client and server in my local:
String sName = "localhost";
Verify your server-name if you are expecting client to connect to server.
Hi I have the following code to the client - server through the thread, I have a errors,
Can't setup server on this port number.
Can't setup server on this port number.
but why?
class client:
import java.io.*;
import java.net.Socket;
// create class client
public class Client extends Thread {
Socket socket = null;
Socket socket1 = null;
// create send method
public void sendFile() throws IOException {
String host = "127.0.0.1";
String host1 = "127.0.0.2";
socket = new Socket(host, 4444);
socket1 = new Socket(host1, 444);
File file = new File("/home/reza/Desktop/link help");
File file1 = new File("/home/reza/Desktop/hi");
long length = file.length();
long length1 = file1.length();
byte[] bytes = new byte[(int) length];
byte[] bytes1 = new byte[(int) length1];
FileInputStream fis = new FileInputStream(file);
FileInputStream fis1 = new FileInputStream(file1);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
BufferedInputStream bis1 = new BufferedInputStream(fis1);
BufferedOutputStream out1 = new BufferedOutputStream(socket1.getOutputStream());
int count;
int count1;
while ((count = bis.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
while ((count1 = bis1.read(bytes1)) > 0) {
out1.write(bytes1, 0, count1);
}
Thread t = new Thread(new Runnable() {
public void run()
{
while(socket.isConnected())
{
Wait2();
try {
sendFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
Thread t1 = new Thread(new Runnable() {
public void run() {
while(socket1.isConnected())
{
Wait2();
try {
sendFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
t.start();
t1.start();
fis.close();
fis1.close();
out.close();
bis.close();
out1.close();
bis1.close();
socket.close();
socket1.close();
}
public void Wait2()
{
try {
Thread.currentThread().sleep(3000);
} catch (InterruptedException x) {
System.out.println("Interrupted!");
}
}
}
// class server
import java.io.*;
import java.net.*;
public class Server {
public void recivefile() throws IOException {
ServerSocket serverSocket = null;
ServerSocket serverSocket1 = null;
try {
serverSocket = new ServerSocket(4444);
//serverSocket1 = new ServerSocket(444);
} catch (IOException ex) {
System.out.println("Can't setup server on this port number. ");
}
try {
serverSocket1 = new ServerSocket(444);
} catch (IOException ex) {
System.out.println("Can't setup server on this port number. ");
}
Socket socket = null;
Socket socket1 = null;
InputStream is = null;
InputStream is1 = null;
FileOutputStream fos = null;
FileOutputStream fos1 = null;
BufferedOutputStream bos = null;
BufferedOutputStream bos1 = null;
int bufferSize = 0;
int bufferSize1 = 0;
try {
socket = serverSocket.accept();
socket1 = serverSocket1.accept();
} catch (IOException ex) {
System.out.println("Can't accept client connection. ");
}
try {
is = socket.getInputStream();
is1 = socket1.getInputStream();
bufferSize = socket.getReceiveBufferSize();
bufferSize1 = socket1.getReceiveBufferSize();
System.out.println("Buffer size: " + bufferSize);
System.out.println("file recieved");
System.out.println("Buffer size1: " + bufferSize1);
System.out.println("file recieved");
System.out.println("file recieved");
} catch (IOException ex) {
System.out.println("Can't get socket input stream. ");
}
try {
fos = new FileOutputStream("/home/reza/Desktop/reza");
bos = new BufferedOutputStream(fos);
fos1 = new FileOutputStream("/home/reza/Desktop/ali");
bos1 = new BufferedOutputStream(fos1);
} catch (FileNotFoundException ex) {
System.out.println("File not found. ");
}
byte[] bytes = new byte[bufferSize];
int count;
while ((count = is.read(bytes)) > 0) {
bos.write(bytes, 0, count);
}
byte[] bytes1 = new byte[bufferSize1];
int count1;
while ((count1 = is1.read(bytes1)) > 0) {
bos1.write(bytes1, 0, count1);
}
bos.flush();
bos.close();
bos1.flush();
bos1.close();
is.close();
is1.close();
socket.close();
serverSocket.close();
socket1.close();
serverSocket1.close();
}
public static void main(String[] args) throws IOException
{
System.out.println("server is run, please send file");
Server s = new Server();
s.recivefile();
}
}
error is :
Can't setup server on this port number.
Can't setup server on this port number.
You can't start a server on 127.0.0.2 - therein lies your problem.
netstat -ano | find "1024"
try above command if you are running your java files on windows environment that will help you to find any process using same port no as yours and also use
ex.printStackTrace() along with
System.out.println("Can't setup server on this port number.");
Assuming that your code runs on a unix platform, your server code is trying twice to open a socket on port 444, which is a system reserved port. In order to be able to succeed, your programme must run with administrative priviledges, and you must ensure that the port is not already used by another process.
A possible workaround is to:
use a port above 1024. These ports are free to use for userland programmes
in case of failure have a backup port, also above 1024. You must amend both server and client codes to try both ports, and of course your communication protocol must include some form of handshaking to make sure they are talking to the right interlocutor.
There are many other problems with your code listed in other answers.
you don't need to make every objects twice. Only one instance is enough in most cases,
if your server is running continuously and must accept many connections, you should not close the accepting socket at the end of one receiving session.
also the server is supposed to run a loop on the server socket accept call, and start a new thread for each incoming connection, whose job is to handle that connection.
While I understand your willingness to learn and experiment, there are existing solutions to what you are trying to achieve. For instance, you could simply use a FTP server for your purpose.
The way you have written client - server program is wrong I guess.
Following are the mistakes you have done...
1) In Client class, you have sendFile function in which you've created two threads - t & t1. In run function you are again calling the same sendFile function.
So it keeps creating threads under threads just like recursion.
2) In Server class, you are listening to two port within the same recieveFile function. As the socket = serverSocket.accept() is a blocking call, It wont excecute the rest of the code untill it finds a single client to connect.
So what exactly happens here is.. Once the first client connects, thenafter immediately it expects second client to connect.
In the mean time your client thread may try to access the port on which connection has not been established.
In short, your SERVER SHOULD BE IN A THREADING ENVIRONMENT NOT THE CLIENT.
And I would suggest that for different port you should use different server.
i.e. create different server class for both 1024 & 1025 port.
I am trying to write server to client program but I cannot communicate with the server in Java.
Here is the code block in my main.
InetAddress addr = InetAddress.getLocalHost();
ipAddress = "78.162.206.164";
ServerSocket serverSocket = new ServerSocket(0);
String randomStringForPlayerName = RandomStringGenerator.generateRandomString();
baseForReqOpp += ipAddress + " " + serverSocket + " " + randomStringForPlayerName;
Socket socket = new Socket(host,2050);
socket.setSoTimeout(100);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream());
out.write(baseForReqOpp);
out.flush();
System.out.println(in.read());
I know that there is no problem in the server code and all the communication ports are ok.
But I cannot read anything from the server.
What can be the problem?
you have to create an output stream before the input stream
Here is some working code with communicating client and server sockets. Hopefully you can adapt it for your specific problem.
public class SocketTest {
public void runTest() {
try {
// create the server
new SimpleServer().start();
// connect and send a message
InetAddress addr = InetAddress.getLocalHost();
Socket sock = new Socket(addr, 9090);
ObjectOutputStream out = new ObjectOutputStream(sock.getOutputStream());
out.writeObject("Hello server");
out.flush();
ObjectInputStream in = new ObjectInputStream(sock.getInputStream());
System.out.println("from server: " + in.readObject());
sock.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// server has to run in a separate thread so the code doesn't block
private class SimpleServer extends Thread {
#Override
public void run() {
try {
ServerSocket sock = new ServerSocket(9090);
Socket conn = sock.accept();
// the code blocks here until a client connects to the server
ObjectInputStream in = new ObjectInputStream(conn.getInputStream());
System.out.println("from client: " + in.readObject());
ObjectOutputStream out = new ObjectOutputStream(conn.getOutputStream());
out.writeObject("Hello client");
out.flush();
sock.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
To run it:
new SocketTest().runTest();
Your code will never work because you don't use threads. In order to start the server, you need to call accept at some point in your code
myServerSocket.accept();
this is a blocking call, ie the code flow stops until a client connects. But since you can't execute any statement (remember accept is blocking?) how can a client connect? This chicken and egg problem is resolved through threads. See Howard's answer for a code sample.
I don't see any call to accept(), so I wonder what your client connects to...