How do you send a text file through sockets? - java

I'm trying to create a simple Client-Server java program. Simple, I need to send a text file (ToSend.txt) from the Server to the client, it's in the same directory where the Server.java is. After running the program, the ToSend.txt file should be in the same directory where the Client.java is, and will be renamed as Received.txt.
Server:
File file = new File("ToSend.txt");
try
{
ServerSocket serverSocket = new ServerSocket(1234);
Socket serverEndpoint = serverSocket.accept();
//what to do here?
serverEndpoint.close();
}
catch (Exception e)
{
e.printStackTrace();
}
Client:
try
{
Socket clientEndpoint = new Socket(localhost, 1234);
//what to do here?
clientEndpoint.close();
}
catch (Exception e)
{
e.printStackTrace();
}
ToSend.txt
Self-learning during a global pandemic is difficult.
I got confused if I will use DataOutputStream or just OutputStream or FileReader, i need help.

First you need to serialize the file then send it, you can't just send a file like that, this has been already answered, so I will not repeat the answer, I will just link an answer other user provided.
Java sending and receiving file (byte[]) over sockets
Try looking up videos how to serialize data in java there are different methods, using bytes like the one linked, this is part of the Java streams tutorial and it is very useful to learn how streams actually operate.

Related

Detect when a client is no longer listening to server

I am writing an application that streams data that clients can then listen to and receive. However I am running into an issue with closing a socket when a client is no longer listening.
What I do is create a ServerSocket, when then waits for a connection and once it is connected, I start streaming the data. However, once the client is no longer connected, I am stuck in a loop of streaming and cannot tell if anyone is listening. Is there a way around this?
try {
serverSocket = new ServerSocket(STREAM_PORT);
Socket clientSocket = serverSocket.accept();
PrintWriter pw = new PrintWriter(clientSocket.getOutputStream(), true);
while (true) {
pw.println("some data");
}
} catch (SocketException e) {
// Never occurs when client disconnects
} catch (IOException e) {
// Never occurs when client disconnects
}
I have tried using socket.isClosed(), but it always returns false. Am I approaching this from the wrong angle, or is there a way to do it. I would ideally not want the client to have to send the server a "end" command.
EDIT: Edited to reflect what current code I am running after #Rod_Algonquin suggestion
As you are using PrintWriter, which swallows I/O exceptions, you need to call checkError() after each write to see if an error has occurred.

Write to remote file java

How can I write to remote file in server? I try this but I canĀ“t
try {
BufferedWriter out = new BufferedWriter(new FileWriter("http://myserver/file.txt"));
out.write("Hello");
out.close();
} catch (IOException e) {
//handle exception
}
You can use the FTP library from Apache to get the file in to your local, modify it, then ftp it back.
2nd option, if you don't want to do heavy text modifying is to use sshExec. It lets you run commands on the server you connect to.
3rd option, execute the class on the server that the txt file exists.

Possible Socket + ServerSocket in java?

We are making an somewhat RTS networked game in java. i have this main server that accepts other players which has the serversocket. Then on our game when you created your own game room
i filtered all the players that has joined my room.then when the game starts the creator of the room should be the host. should i be still using my main server or should i establish a new serversocket for those who are connected to my room? and 1 more thing should a inputstream.readObject() what for an message to go for another loop?or it continuously looping? here is the sample code snippet for the inputstream.
public void run() {
while (running) {
try {
inStream = new ObjectInputStream(client.getInputStream());
command = (String) inStream.readObject();
Thread.sleep(10);
}//try
catch (Exception e) {
e.printStackTrace();
}//catch
}//while
}//run
////accepting new client
while (running) {
try {
clientConnecting = serverSocket.accept();
new TCPServerHandle(clientConnecting).start();
Thread.sleep(10);
}//try
catch (Exception e) {
e.printStackTrace();
}//catch
}//while
You could deffinitely create a second ServerSocket for the "party" to communicate with the host. Incoming packets are demultiplexed to the correct process, using port numbers. You can set multiple TCPServerSockets to listen and accept incoming connection requests on different ports.
ServerSocket welcomeSocket = new ServerSocket(portNumber);
Socket clientSocket = welcomeSocket.accept();
And yes, it is in many cases more efficient to use a combination of TCP and UDP, because as you mention some data is more critical than other. UDP only provides a best effort service, where packets can get lost. If you want to setup a UDP socket:
DatagramSocket UDPSocket = new DatagramSocket();
Using blocking I/O with Object I/O streams aren't optimal conditions for an RTS because you don't want other clients to wait during the login process of another client. You might be thinking that you could just multi-thread everything to avoid the wait but it wouldn't make much of a difference because there are still blocking read/write operations. Also, with Object I/O streams, all objects sent have to be serialized first (known as serialization), which could be a pretty lengthy process depending on your user-base. If there are a lot of players, literally every millisecond counts. You should use non-blocking I/O (such as NIO) along with ByteBuffers. I would suggest looking at an NIO tutorial instead, this is a very detailed tutorial on how to make a simple server-client application.

I can't get more than one applet communicating with my Cpp server

For some reason when I connect one Java client to my Cpp server it works perfectly. But when another Java applet tries to connect in addition to the first, it does but it stops receiving data from the server. Some of the other attempts would completly freeze the applet. I have searched everywhere on the 'net but found nothing. I would appreciate any help on the subject like advice, links or source. My only other option (since Flash is out of the question) is to use Active X, but then I would lose all my crossplatform-ability :(. My source (minus debugging code and so on) follows.
public void init() {
try {
socket = new Socket("localhost",4000);
} catch (UnknownHostException e) {
System.out.println("Unknown host");
} catch (IOException e) {
System.out.println("IO Exception");
return;
}
BufferedReader fromServer = null;
PrintWriter toServer = null;
fromServer = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
toServer =
new PrintWriter(socket.getOutputStream(), true);
toServer.flush();
It sounds like your Cpp server can't handle multiple connections. Can you verify that you can accept more than one incoming network connection?
I found the solution! You can't run multiple applets in one browser and one machine. It will work if you load them in seperate browsers (like IE and FF) or load it on a seperate machine (like remotely). I hope this helps.

Java client/server application with sockets?

I'm writing a java package that will be called by another language (matlab). If my matlab process ends, I want the Java process to keep running. Whenever matlab starts again, it should be able to communicate with the existing running process. So I think I need to have the Java application communicating through sockets in a client/server model. I envision having a simple set of functions:
startServer(host, port)
runCommand(server, command...)
stopServer(host, port)
I have never done anything like this before. Am I thinking about it in the right way, or is there an easier way of building an application that can run independently of it's parent's process? What's the best modern way of doing this (e.g. are there any good Apache packages)? Can anyone provide a simple demo or point me to a tutorial on communicating with a process through sockets?
[Edit] For some clarification, matlab is able to instantiate a java object and run java code within itself. So the startServer() function in matlab would run java code that will check if a java process is already running on that port and if not, start the server process.
I'm not tied to using sockets by any means (in case it isn't obvious, I'm mostly a matlab developer), so if there's something easier, I'm all for it. I just need to be able to run things independently of matlab, but have matlab control those processes (through java).
The server listens for a connection. When a connection is established by a client. The client can send data. In the current example the client sends the message "Hi my server". To terminate the connection, the client sends the message "bye". Then the server sends the message "bye" too. Finally the connection is ended and the server waits for an other connection. The two programs should be running in the same machine. however if you want to run them in two different machines, you may simply change the address "localhost" by the IP address of the machine where you will run the server.
The server
import java.io.*;
import java.net.*;
public class Provider{
ServerSocket providerSocket;
Socket connection = null;
ObjectOutputStream out;
ObjectInputStream in;
String message;
Provider(){}
void run()
{
try{
//1. creating a server socket
providerSocket = new ServerSocket(2004, 10);
//2. Wait for connection
System.out.println("Waiting for connection");
connection = providerSocket.accept();
System.out.println("Connection received from " + connection.getInetAddress().getHostName());
//3. get Input and Output streams
out = new ObjectOutputStream(connection.getOutputStream());
out.flush();
in = new ObjectInputStream(connection.getInputStream());
sendMessage("Connection successful");
//4. The two parts communicate via the input and output streams
do{
try{
message = (String)in.readObject();
System.out.println("client>" + message);
if (message.equals("bye"))
sendMessage("bye");
}
catch(ClassNotFoundException classnot){
System.err.println("Data received in unknown format");
}
}while(!message.equals("bye"));
}
catch(IOException ioException){
ioException.printStackTrace();
}
finally{
//4: Closing connection
try{
in.close();
out.close();
providerSocket.close();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
}
void sendMessage(String msg)
{
try{
out.writeObject(msg);
out.flush();
System.out.println("server>" + msg);
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
public static void main(String args[])
{
Provider server = new Provider();
while(true){
server.run();
}
}
}
The client
import java.io.*;
import java.net.*;
public class Requester{
Socket requestSocket;
ObjectOutputStream out;
ObjectInputStream in;
String message;
Requester(){}
void run()
{
try{
//1. creating a socket to connect to the server
requestSocket = new Socket("localhost", 2004);
System.out.println("Connected to localhost in port 2004");
//2. get Input and Output streams
out = new ObjectOutputStream(requestSocket.getOutputStream());
out.flush();
in = new ObjectInputStream(requestSocket.getInputStream());
//3: Communicating with the server
do{
try{
message = (String)in.readObject();
System.out.println("server>" + message);
sendMessage("Hi my server");
message = "bye";
sendMessage(message);
}
catch(ClassNotFoundException classNot){
System.err.println("data received in unknown format");
}
}while(!message.equals("bye"));
}
catch(UnknownHostException unknownHost){
System.err.println("You are trying to connect to an unknown host!");
}
catch(IOException ioException){
ioException.printStackTrace();
}
finally{
//4: Closing connection
try{
in.close();
out.close();
requestSocket.close();
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
}
void sendMessage(String msg)
{
try{
out.writeObject(msg);
out.flush();
System.out.println("client>" + msg);
}
catch(IOException ioException){
ioException.printStackTrace();
}
}
public static void main(String args[])
{
Requester client = new Requester();
client.run();
}
}
If you decide to go with a custom socket-level protocol, then I can suggest that you use JBoss Netty at the java end:
In other words, Netty is a NIO client
server framework which enables quick
and easy development of network
applications such as protocol servers
and clients. It greatly simplifies and
streamlines network programming such
as TCP and UDP socket server.
It sounds like you need the Java server process to be independent of the Matlab process. So when the Matlab process starts/stops, the Java server continues. The Java server will sit and wait for incoming connections, and handle multiple connections, disconnects etc.
Here's a tutorial for writing a Java socket server (note it's part of a larger tutorial on Java client/server socket communication).
One challenge you will face (and I can't help you here being Matlab-unaware) is creating or using a platform-independent means of creating the actual message, whether that's using a binary representation, XML (looks like Matlab has some XML functionality) or other.
If, as you say, matlab can run java code from within itself, then there should be no reason that you can't use RMI to communicate between matlab and java server. RMI is vastly easier than raw socket programming.
The easy part is the tutorial: Sun's Sockets Tutorial taught me everything I needed to know about sockets programming, and will hopefully do for you too.
I think you need to clarify your thinking about the commands you want to support, in particular the first and 3rd:
If the Java process isn't running, who's going to respond to your startServer command? And if it is running, who needs it? :)
You can certainly implement a stopServer command. But that would be kind of like having your computer pulling its own power cord out of the wall. We return to the previous question: If the server's stopped, who'll hear the start command?
As I understand it, the only remote operation you need is the middle one.
However... socket programming is only moderately fun. You may consider looking at the RMI tutorial for an alternative.
Any reason that you can't just implement your java server as a collection of servlets in tomcat? Tomcat comes with all the tools to autostart and keep the server running, you can implement SOAP service or RESTful web services pretty easily which will help to decouple your matlab code from your java code.

Categories

Resources