Problem with sending .mkv files with socket in java - java

I am trying to send a .mkv file with a Java server socket. The file is beeing transmitted normally but when I try to open it with VLC Media Player it only shows the first second of the film and then the pircture freezes.
Server:
public class Server {
public void run_server(){
try {
ExecutorService executorService = Executors.newFixedThreadPool(100);
ServerSocket server = new ServerSocket(1234);
System.out.println("Waiting for client at port " + server.getLocalPort() + "\n");
while (true) {
Socket client = server.accept();
executorService.execute(new Handler(client));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Server s = new Server();
s.run_server();
}
public class Handler implements Runnable {
private Socket client;
public Handler(Socket client) {
this.client = client;
}
#Override
public void run() {
try {
System.out.println("client connected: " + client.getInetAddress());
FileInputStream fin = new FileInputStream("D:\\Filme\\Asterix und das Geheimnis des Zaubertranks (2018).mkv");
byte[] buffer = new byte[522231808];
fin.read(buffer,0,buffer.length);
DataOutputStream out = new DataOutputStream(client.getOutputStream());
out.write(buffer,0,buffer.length);
} catch (Exception e) {
e.printStackTrace();
}
}
The client:
public static void main(String[] args) {
new Thread(new Client()).start();
}
#Override
public void run() {
try {
Socket client = new Socket("localhost", 1234);
DataInputStream in = new DataInputStream(client.getInputStream());
FileOutputStream fout = new FileOutputStream("D:\\test\\test.mkv");
byte[] buffer = new byte[522231808];
in.read(buffer,0,buffer.length);
fout.write(buffer,0,buffer.length);
} catch (IOException e) {
e.printStackTrace();
}
}
Where is the problem?
Thanks in advance

Try a smaller buffer:
byte[] buffer = new byte[16384];
for (int n = in.read(buffer); n > 0; n = in.read(buffer)) {
fout.write(buffer,0,n);
}

Related

Java socket handle multiple clients

I have a server and a client the client already connects successfully to the server even if i start another client it connects successfully and here is my problem the clients can send data to the server (its basically only a string)the server gets the data of both clients but the clients only get their own data back and i would like to have that both clients get the same data from the server back.
Server:
public class Server extends Application {
#Override
public void start(Stage primaryStage) {
}
static ServerSocket serverSocket;
static Socket socket;
static DataOutputStream out;
static DataInputStream in;
static Users[] user = new Users[10];
public static void main(String[] args) throws IOException {
System.out.println("Starting server...");
serverSocket = new ServerSocket(7777);
System.out.println("Server started");
while(true){
socket = serverSocket.accept();
for(int i = 0;i < 10; i++){
System.out.println("Connection from:" + socket.getInetAddress());
out = new DataOutputStream(socket.getOutputStream());
in = new DataInputStream(socket.getInputStream());
if(user[i] == null){
user[i] = new Users(out,in,user);
Thread thread = new Thread(user[i]);
thread.start();
break;
}
}
}
}
private static class Users implements Runnable{
DataOutputStream out;
DataInputStream in;
Users[] user = new Users[10];
String name;
public Users(DataOutputStream out,DataInputStream in,Users[] user){
this.out = out;
this.in = in;
this.user = user;
}
#Override
public void run() {
while(true){
try {
String recievingData = in.readUTF();
System.out.println(recievingData);
out.writeUTF(recievingData);
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}}}
Client(both are the same):
public class ServerClient {
static Socket socket;
static DataInputStream in;
static DataOutputStream out;
public ServerClient() throws IOException{
System.out.println("Connecting");
socket = new Socket("localhost",7777);
System.out.println("Connecting succesful");
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
System.out.println("Recieving");
Input input = new Input(in);
Thread thread = new Thread(input);
thread.start();
}
public static void UploadPos(){
try {
out.writeUTF("TEST");
} catch (IOException ex) {
Logger.getLogger(ServerClient.class.getName()).log(Level.SEVERE, null, ex);
}
}}
class Input implements Runnable{
DataOutputStream out;
DataInputStream in;
public Input(DataInputStream in){
this.in = in;
}
#Override
public void run() {
while(true){
try {
String data = in.readUTF();
System.out.println(data);
} catch (IOException ex) {
Logger.getLogger(Input.class.getName()).log(Level.SEVERE, null, ex);
}
}
}}
Create a list of output streams.
List<DataOutputStream> clientOuts = new ArrayList<>();
after
out = new DataOutputStream(socket.getOutputStream());
add
clientOuts.add(out);
then replace
out.writeUTF(recievingData);
with
for(DataOutputStream cout :clientOutputs) {
cout.writeUTF(recievingData);
}

App freezes when trying to send an object via a socket

Let me jump right in. Here's my Server class:
public class DTServer {
ServerSocket serverSocket;
ServerSocketHints serverSocketHints;
Socket socket;
InputStream inputStream;
OutputStream outputStream;
ObjectInputStream objectInputStream;
ObjectOutputStream objectOutputStream;
public DTServer(int port) {
serverSocketHints = new ServerSocketHints();
serverSocketHints.acceptTimeout = 0;
serverSocket = Gdx.net.newServerSocket(
Net.Protocol.TCP, port, serverSocketHints);
socket = serverSocket.accept(null);
}
public Serialized receiveSerialized() {
inputStream = socket.getInputStream();
try {
objectInputStream = new ObjectInputStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
outputStream = socket.getOutputStream();
try {
objectOutputStream = new ObjectOutputStream(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
Serialized serialized = new Serialized();
try {
serialized = (Serialized) objectInputStream.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return serialized;
}
}
And the Client class:
public class DTClient {
Socket socket;
SocketHints socketHints;
InputStream inputStream;
OutputStream outputStream;
ObjectInputStream objectInputStream;
ObjectOutputStream objectOutputStream;
public DTClient(String address, int port) {
socketHints = new SocketHints();
socketHints.connectTimeout = 3000;
socketHints.keepAlive = true;
// socketHints.trafficClass = 0x04; //IPTOS_RELIABILITY
socket = Gdx.net.newClientSocket(
Net.Protocol.TCP, address, port, socketHints);
}
public void sendSerialized(Serialized serialized) {
inputStream = socket.getInputStream();
try {
objectInputStream = new ObjectInputStream(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
outputStream = socket.getOutputStream();
try {
objectOutputStream = new ObjectOutputStream(outputStream);
} catch (IOException e) {
e.printStackTrace();
}
try {
objectOutputStream.writeObject(serialized);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I create the server object like this:
public void startServer() {
new Thread(new Runnable() {
#Override
public void run() {
dtServer = new DTServer(32658);
System.out.println("Server started and listening at port: 32658.");
}
}).start();
}
And then connect to it with other instance of the program:
public void connect() {
new Thread(new Runnable() {
#Override
public void run() {
dtClient = new DTClient("127.0.0.1", 32658);
System.out.println("Connected to server at 127.0.0.1:32658");
}
}).start();
}
And everything work swell until I try to receive the object I sent:
game.dtClient.sendSerialized(new Serialized(game.gameScreen.localPlayer));
//client side
Serialized s = (Serialized)game.dtServer.receiveSerialized();
//server side
Calling receiveSerialized method causes both app instances to freeze.
Create the ObjectOutputStream before the ObjectInputStream, at both ends. Otherwise you can get a deadlock trying to read the object stream header.
You should also use the same object streams for the life of the socket, rather than a new pair per message.

Maximum socket connections available

I am trying my hand at socket programming. I built a simple echo server that prints the client text on the screen and sends back a thank you message to the client. However when I run the client (which individually spawns 10000 requests in a loop) sometimes i get "connection refused" exceptions in some client threads. Sometimes all go through without any exception.
Following is my server code :
public class WebServer {
static int hitCount = 0;
public static void main(String[] args) throws Exception {
ServerSocket serverSocket = new ServerSocket(7777, 10000);
while (true) {
Socket defaultSocket = serverSocket.accept();
new Thread(new ServerSlave(defaultSocket)).start();
System.out.println("Size is :" + hitCount);
}
}
}
class ServerSlave implements Runnable {
Socket clientSocket;
public ServerSlave(Socket socket) {
clientSocket = socket;
WebServer.hitCount++;
}
public void run() {
try {
DataInputStream inputStream = new DataInputStream(clientSocket.getInputStream());
DataOutputStream outputStream = new DataOutputStream(clientSocket.getOutputStream());
System.out.println(inputStream.readUTF());
outputStream.writeUTF("Thank you for contacting the web server");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Following is my client code :
public class Client {
static int excepCount=0;
public static void main(String[] args) throws Exception {
for (int i = 0; i < 10000; i++) {
new Thread(new Worker("" + i)).start();
}
Thread.sleep(10000);
System.out.println( Client.excepCount);
}
}
class Worker implements Runnable {
String clientName;
public Worker(String name) {
clientName = name;
}
public void run() {
System.out.println("Process started for : " + clientName);
Socket socket = null;
try {
socket = new Socket("127.0.0.1", 7777);
DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream());
outputStream.writeUTF("Hello socket. Client number " + clientName + "here");
InputStream inFromServer = socket.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
System.out.println("Closing socket");
} catch (IOException e) {
Client.excepCount++;
e.printStackTrace();
}finally{
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Not sure what I might be doing wrong. Any suggestions ?
You're expecting too much. It just isn't realistic for a client to form 10,000 connections at maximum speed. You're forgetting about the TIME_WAIT state, and the fact that there are only 64k minus several dozen client-side ports available. It isn't a realistic test. If you want to load-test your server you will need quite a few client hosts, or a longer interval between connections.

I'm trying to send protocol buffer message to server several times but server only got the first one

I'm trying to send protocol buffer message to server several times but server
only got the first one, the output is like this
msgContent:
xxxxxxxxxxxxxxxxxxx
and this thing only show once when I think it should show ten times
anyone can help me ? thanks very much..
//server
public class Main {
public static void main (String[] args) {
Thread serverThread = new Thread() {
private ServerSocket server;
#Override
public void run() {
try {
while(true) {
try {
if (server == null) {
server = new ServerSocket(8080);
}
Socket client = server.accept();
InputStream is = client.getInputStream();
TestProto.Test test = TestProto.Test.parseDelimitedFrom(is);
System.out.println("msgContent: \n" + test.getId());
} catch (Exception ex) {
}
}
} catch (Exception ex) {
}
}
};
serverThread.start();
}
}
///////////////////////////////////////client
public class Client {
private static void sendProtoc(){
try {
TestProto.Test test = TestProto.Test.newBuilder().setId("xxxxxxxxxxxxxxx").build();
Socket socket = new Socket("localhost", 8080);
OutputStream os = socket.getOutputStream();
int msgType = 1;
test.writeDelimitedTo(os);
os.flush();
} catch (Exception ex) {
}
}
public static void main(String[] args) {
for(int i = 0; i < 10; ++i) {
sendProtoc();
System.out.println("sent " + i);
}
}
}

client server with multi threading

i write a program client-server with multi threading for send - receive file. The program runs and client send and server receive. the files are created but empty new files are created
Why? please help me
class client :
import java.io.*;
import java.net.Socket;
public class Client extends Thread {
Socket socket = null;
Socket socket1 = null;
public void sendFile() throws IOException {
String host = "127.0.0.1";
String host1 = "127.0.0.2";
socket = new Socket(host, 1024);
socket1 = new Socket(host1, 1025);
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();
final byte[] bytes = new byte[(int) length];
final byte[] bytes1 = new byte[(int) length1];
FileInputStream fis = new FileInputStream(file);
FileInputStream fis1 = new FileInputStream(file1);
#SuppressWarnings("resource")
final BufferedInputStream bis = new BufferedInputStream(fis);
final BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
#SuppressWarnings("resource")
final BufferedInputStream bis1 = new BufferedInputStream(fis1);
final BufferedOutputStream out1 = new BufferedOutputStream(socket1.getOutputStream());
Thread t = new Thread(new Runnable() {
public void run()
{
while(socket.isConnected())
{
Wait2();
try {
System.out.println("ok");
int count;
while ((count = bis.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
Thread t1 = new Thread(new Runnable() {
public void run() {
while(socket1.isConnected())
{
Wait2();
try {
System.out.println("ok1");
int count1;
while ((count1 = bis1.read(bytes1)) > 0) {
out1.write(bytes1, 0, count1);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
t1.start();
t.start();
socket.close();
socket1.close();
}
public void Wait2()
{
try {
Thread.sleep(3000);
} catch (InterruptedException x) {
System.out.println("Interrupted!");
}
}
}
class server:
import java.io.*;
import java.net.*;
public class Server {
public Server()
{
Thread t = new Thread(new Client());
t.start();
Thread t1 = new Thread(new Client());
t1.start();
}
//#SuppressWarnings("null")
public void recivefile() throws IOException {
ServerSocket serverSocket = null;
ServerSocket serverSocket1 = null;
try {
serverSocket = new ServerSocket(1024);
} catch (IOException ex) {
System.out.println("Can't setup server on this port number. ");
}
try {
serverSocket1 = new ServerSocket(1025);
} catch (IOException ex) {
System.out.println("Can't setup server on this port number1. ");
}
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();
//bufferSize2 = socket2.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();
}
}
client test class:
import java.io.IOException;
public class clientTest extends Thread {
public static void main(String[] args) throws IOException, InterruptedException
{
Client client = new Client();
client.sendFile();
}
}
I believe this code in the server to be your issue:
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();
So the server has connected to the client, then it immediately checks to see if there are any bytes to read, if not it stops reading and closes the connection. If this happens faster than the client can deliver any bytes, boom, no data is received. And it WILL happend faster than the client can send data because the client is connecting THEN starting thread to send the data.
Instead, the server should read on each connection for as long as the client has maintained the connection alive. The server needs to wait for the data to be received.
Notice that in your code, the client is waiting for the server to close the connection. But how is the server supposed to know when all the data is sent? Either the client must close the connection or the client must send an EOF-type marker to the server indicating an end of the data and that it is safe to close the connection.

Categories

Resources