It errors at the last line in the client code, with the code. java.io.StreamCorruptedException: invalid stream header: 36353137. I haven't done anything to the stream before this point, so I am unsure what could be causing the problem with the ObjectInputStream.
The server class works properly, and follows the behavior I set for it, it is only the client class that is erroring.
I thought the problem at first might be because the stream wasn't being flushed, but flushing it did not fix the issue.
Apart from that, since this error is happening so early in the code, I am at a loss as to what to add to fix it.
Client class -
import java.io.*;
import java.net.*;
public class tcpClient {
int nonce;
Socket requestSocket;
ObjectOutputStream out;
ObjectInputStream in;
String message;
tcpClient(){}
void run()
{
try{
requestSocket = new Socket("localhost", 3223);
System.out.println("Connected to localhost in port 3223");
out = new ObjectOutputStream(requestSocket.getOutputStream());
out.flush();
in = new ObjectInputStream(requestSocket.getInputStream());
Server Class -
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Calendar;
import java.util.Random;
import java.util.Scanner;
import javax.swing.Timer;
public class TCPMasterServer
implements ActionListener
{
ServerSocket server;
Socket client;
Random random;
Calendar rightNow;
Timer timer;
String ipaddress;
PrintWriter out;
BufferedReader ir;
public TCPMasterServer()
{
this.random = new Random();
this.rightNow = Calendar.getInstance();
try
{
this.server = new ServerSocket(3223);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private void listenForConnection()
{
try
{
this.client = this.server.accept();
this.ipaddress = this.client.getInetAddress().getHostAddress();
System.out.println(this.rightNow.getTime() + ": Connected from: " + this.ipaddress);
this.out = new PrintWriter(this.client.getOutputStream(), true);
this.ir = new BufferedReader(new InputStreamReader(this.client.getInputStream()));
communicateWithClient();
}
catch (Exception e)
{
e.printStackTrace();
listenForConnection();
}
}
private void communicateWithClient()
{
this.timer = new Timer(2000, this);
this.timer.setRepeats(false);
this.timer.start();
try
{
int nonce = this.random.nextInt(1000000);
this.out.println(nonce);
System.out.println(this.rightNow.getTime() + ": Send nonce: " + nonce);
String input = this.ir.readLine();
Scanner in = new Scanner(input);
int nonceResponse = in.nextInt();
System.out.print(this.rightNow.getTime() + ": Received number: " + nonceResponse);
if (nonceResponse == nonce + 1)
{
System.out.println("... OK");
this.out.println("SEND_NAME");
System.out.println(this.rightNow.getTime() + ": Request name");
input = this.ir.readLine();
System.out.println(this.rightNow.getTime() + ": Received name: " + input);
this.out.println(input + " ACK");
System.out.println(this.rightNow.getTime() + ": ACK sent");
}
this.client.close();
}
catch (Exception ex)
{
System.out.println(this.rightNow.getTime() + ": Error happened. Giving up");
}
this.timer.stop();
System.out.println();
listenForConnection();
}
public void actionPerformed(ActionEvent evt)
{
try
{
System.out.println("Timer fired.");
this.client.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
TCPMasterServer server = new TCPMasterServer();
server.listenForConnection();
}
}
You're using object streams at the server, but readers and writers at the client. That won't work. If you want to read objects you must write objects.
Related
so i'm trying to create a chess server for a chess application i wrote in java. The two classes i'm including are the main class that starts my TCPServerThreads and this class itselve.
I am able to connect two clients and for example echo their input back to them, but i have no idea, how to exchange information between these two threads. I am trying to forward Server inputs from one client towards the main class, or directly to the other client, so i can update the chess field on the client.
It's pretty much my first time working with servers, so thanks in advance for you patience.
This is my main class:
package Main;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import TCP.TCPServerThread;
public class Main {
public static final String StopCode = "STOP";
public static final int PORT = 8888;
public static int count = 0;
public static void main(String[] args) {
ServerSocket serverSocket = null;
Socket socket = null;
//create Server Socket
try {
serverSocket = new ServerSocket(PORT);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("serverSocket created");
//accept client Sockets
while (count < 2) {
try {
socket = serverSocket.accept();
count ++;
System.out.println("socket Nr " + count + " accepted");
} catch (IOException e) {
System.out.println("I/O error: " + e);
}
// new thread for a client
new TCPServerThread(socket).start();
}
}
}
And this is the TCPServerThread:
package TCP;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.sql.Timestamp;
import Main.Main;
public class TCPServerThread extends Thread{
Timestamp ts;
private int port = 0;
Socket socket;
public TCPServerThread(Socket clientSocket) {
this.socket = clientSocket;
}
public void run() {
InputStream is = null;
BufferedReader br = null;
DataOutputStream os = null;
try {
is = socket.getInputStream();
br = new BufferedReader(new InputStreamReader(is));
os = new DataOutputStream(socket.getOutputStream());
} catch (IOException e) {
return;
}
String line;
while (true) {
try {
line = br.readLine();
if ((line == null) || line.equalsIgnoreCase("QUIT")) {
socket.close();
return;
} else {
if(line.equalsIgnoreCase("sp") && this.activeCount() == 3) {
os.writeBytes("1" + "\n\r");
os.flush();
}
os.writeBytes("Echo reply: " + line + "\n\r");
os.flush();
}
} catch (IOException e) {
e.printStackTrace();
return;
}
}
}
}
Thank you very much! I made the tcp threads implement runnable instead of extend thread. Then i added a ConnectionManager between the main and the TCPThreads which isn't static. This way i can put the manager into the TCPThreads constructor and communicate between its objects.
I want to create simple communicator with one server and few clients who could connect and send data to it. It works fine without any threads, with only one client, but once i try to incorporate concurrency it doesn't work. From client perspective there is some connection, I can send data, but there is no sign of receiving that data on server. Here is the server class:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class MyServerSocket implements Runnable
{
private ServerSocket serverSocket;
public MyServerSocket() throws Exception
{
Random generator = new Random();
this.serverSocket = new ServerSocket(generator.nextInt(65000 - 60000) + 60000, 50, InetAddress.getByName("192.168.0.105"));
}
public InetAddress getSocketIPAddress()
{
return this.serverSocket.getInetAddress();
}
public int getPort()
{
return this.serverSocket.getLocalPort();
}
public void run()
{
while (true)
{
System.out.println("Running a thread");
try
{
String data = null;
Socket client = this.serverSocket.accept();
String clientAddress = client.getInetAddress().getHostName();
System.out.println("Connection from: " + clientAddress);
System.out.println("Here I am");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
String message = "";
while ((data = in.readLine()) != null && data.compareToIgnoreCase("quit") != 0)
{
message = ("\r\nMessage from " + clientAddress + ": " + data);
System.out.println(message);
out.write(message);
}
} catch (Exception e)
{
System.out.println("Something went wrong");
} finally
{
try
{
serverSocket.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
Server main:
import java.lang.Thread;
public class Main
{
public static void main(String[] args)
{
try
{
MyServerSocket socket = new MyServerSocket();
Runnable runnable = new MyServerSocket();
System.out.println("Port number: " + socket.getPort() + " IP address: " + socket.getSocketIPAddress());
Thread thread = new Thread(runnable);
thread.start();
}catch (Exception e)
{
e.printStackTrace();
}
}
}
Client class:
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;
public class ClientSocket
{
private Socket socket;
private Scanner scanner;
ClientSocket(InetAddress serverAddress, int serverPort) throws Exception
{
this.socket = new Socket(serverAddress, serverPort);
this.scanner = new Scanner(System.in);
}
public void sendData() throws Exception
{
String data;
System.out.println("Please type in the message. If you want to terminate the connection, type Quit");
PrintWriter out = new PrintWriter(this.socket.getOutputStream(), true);
do
{
data = scanner.nextLine();
out.println(data);
out.flush();
}while(data.compareToIgnoreCase("quit") != 0);
out.println();
}
}
Client main:
import java.net.InetAddress;
import java.util.Scanner;
public class Main
{
public static void main(String[] args)
{
Scanner scanner = new Scanner(System.in);
int port;
System.out.println("Provide port at which you will communicate with the server");
port = scanner.nextInt();
try
{
ClientSocket socket1 = new ClientSocket(InetAddress.getByName("192.168.0.105"), port);
socket1.sendData();
}catch(Exception e)
{
System.out.println("Could not connect to the server.");
}
}
}
Server somehow stops its working when is about to accept the client connection, while client works fine and seem to be connected to the server.
In server side, once you accept a client connection, you should new a thread to process this connection:
import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Random;
public class MyServerSocket implements Runnable {
private ServerSocket serverSocket;
public MyServerSocket() throws Exception {
Random generator = new Random();
this.serverSocket = new ServerSocket(generator.nextInt(65000 - 60000) + 60000, 50, InetAddress.getByName("192.168.0.105"));
}
public InetAddress getSocketIPAddress() {
return this.serverSocket.getInetAddress();
}
public int getPort() {
return this.serverSocket.getLocalPort();
}
public void run() {
while (true) {
System.out.println("Running a thread");
try(Socket client = this.serverSocket.accept()) {
// new thread to process this client
new Thread(() -> {
try {
String data = null;
String clientAddress = client.getInetAddress().getHostName();
System.out.println("Connection from: " + clientAddress);
System.out.println("Here I am");
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
String message = "";
while (true) {
if (!((data = in.readLine()) != null && data.compareToIgnoreCase("quit") != 0)) break;
message = ("\r\nMessage from " + clientAddress + ": " + data);
System.out.println(message);
out.write(message);
}
} catch (IOException e) {
System.out.println("Something went wrong");
}
}).start();
} catch (Exception e) {
System.out.println("Something went wrong");
}
}
}
}
Ok, somehow I solved that problem, but still I need to understand how does it work:
Accepting connection inside try block, without finally block (nor try with resources) so socket is opened all the time.
Modified main method so there is no threads or runnable objects at all in it. The whole process is done within the class:
Code:
public class Main
{
public static void main(String[] args)
{
try
{
MyServerSocket socket = new MyServerSocket();
System.out.println("Port number: " + socket.getPort() + " IP address: " + socket.getSocketIPAddress());
socket.run();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
If anyone could point me out mistakes that are still in this final version of code I'll be grateful.
I'm trying made a simple video stream with Java.I got that play some mp4 video,but not all. On the other hand, I can't seek the stream when the video is playing(Tried in VLC and Chrome). I like to know: What problems does my code have?
Here is the code:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Xerver {
protected void start() {
ServerSocket s;
Socket remote;
OutputStream out;
System.out.println("Webserver starting up on port 8080");
try {
// create the main server socket
s = new ServerSocket(8080);
} catch (IOException e) {
System.out.println("Error: " + e);
return;
}
System.out.println("Waiting for connection");
for (;;) {
try {
// wait for a connection
remote = s.accept();
// remote is now the connected socket
System.out.println("Connection, sending data.");
BufferedReader in = new BufferedReader(new InputStreamReader(remote.getInputStream()));
FileInputStream fs;
out = remote.getOutputStream();
File file = new File("D:\\stream.mp4");
out.write("HTTP/1.0 200 OK\r\n".getBytes());
out.write("Content-Type: video/mp4\r\n".getBytes());
out.write("Accept-Ranges: bytes\r\n".getBytes());
out.write(String.format("Content-Length:%s\r\n\r\n",Long.toString(file.length())).getBytes());
fs = new FileInputStream(file);
final byte[] buffer = new byte[1024];
int count = 0;
do{
count = fs.read(buffer);
out.write(buffer, 0, count);
}
while (count <= 1024);
out.flush();
remote.close();
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
public static void main(String args[]) {
Xerver ws = new Xerver();
ws.start();
}
}
Thanks in advance
I am writing a server-client chat program.
Here is my code
SERVER:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class HelloServer {
public final static int defaultPort = 2345;
public static void main(String[] args) {
int port = defaultPort;
try {
port = Integer.parseInt(args[0]);
} catch (Exception e) {
}
if (port <= 0 || port >= 65536) {
port = defaultPort;
}
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
try {
Socket s = ss.accept();
String response = "Hello " + s.getInetAddress() + " on port " + s.getPort()
+ "\r\n";
response += "This is " + s.getLocalAddress() + " on port " + s.getLocalPort()
+ "\r\n";
OutputStream out = s.getOutputStream();
out.write(response.getBytes());
System.out.write(response.getBytes());
InputStream in = s.getInputStream();
System.out.println("from client");
int z = 0;
while ((z = in.read()) != -1) {
System.out.write(z);
}
} catch (IOException e) {
}
}
} catch (IOException e) {
System.err.println(e);
}
}
}
CLIENT:
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketGetINetAdd {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("192.xxx.x.xxx", 2345);
InetAddress inetAddress = socket.getInetAddress();
System.out.println("Connected to:: " + inetAddress.getHostName() + " Local address:: "
+ socket.getLocalAddress() + " Local Port:: " + socket.getLocalPort());
BufferedInputStream bfINPUT = new BufferedInputStream(socket.getInputStream());
int b = 0;
OutputStream os = System.out;
while ((b = bfINPUT.read()) != -1) {
os.write(b);
}
OutputStream osNew = socket.getOutputStream();
String s = "This Is The Client"; // data to be sent
osNew.write(s.getBytes());
os.write(s.getBytes());
}
I've connected them through my program.
But now I want to know How to send some data back to the server from client?
What would be the code for client(for sending data to server) and also the code for the server for showing the data received from the client on the console(server)?
P.S- I am a novice in network programming. Please do not criticize my coding style :P
Use server stream
OutputStream os = socket.getOutputStream();
instead of client console output stream
OutputStream os = System.out;
at client side to write back to server.
and at server side use client stream to read from client in the same manner.
InputStream in = s.getInputStream();
I have already posted a sample code on server-client communication. Read it for your learning.
You need threads. The client in this examples read the lines from the System.in and sends the line to the server. The server sends an echo.
In your real application you have to take a look of the encoding
Server
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class HelloServer {
public final static int defaultPort = 2345;
public static void main(String[] args) {
int port = defaultPort;
try {
port = Integer.parseInt(args[0]);
} catch (Exception e) {
}
if (port <= 0 || port >= 65536) {
port = defaultPort;
}
try {
ServerSocket ss = new ServerSocket(port);
while (true) {
try {
Socket s = ss.accept();
new SocketThread(s).start();
} catch (IOException e) {
}
}
} catch (IOException e) {
System.err.println(e);
}
}
public static class SocketThread extends Thread {
private Socket s;
public SocketThread(Socket s) {
this.s = s;
}
#Override
public void run() {
try {
String response = "Hello " + s.getInetAddress() + " on port "
+ s.getPort() + "\r\n";
response += "This is " + s.getLocalAddress() + " on port "
+ s.getLocalPort() + "\r\n";
OutputStream out = s.getOutputStream();
out.write(response.getBytes());
BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
while (true) {
String line = input.readLine();
System.out.println("IN: " + line);
s.getOutputStream().write(("ECHO " + line + "\n").getBytes());
s.getOutputStream().flush();
System.out.println(line);
}
} catch (IOException e) {
System.err.println(e);
}
}
}
}
Client
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketGetINetAdd {
public static void main(String[] args) throws UnknownHostException, IOException {
Socket socket = new Socket("localhost", 2345);
InetAddress inetAddress = socket.getInetAddress();
System.out.println("Connected to:: " + inetAddress.getHostName() + " Local address:: " + socket.getLocalAddress() + " Local Port:: " + socket.getLocalPort());
new OutputThread(socket.getInputStream()).start();
InputStreamReader consoleReader = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(consoleReader);
while (true) {
String inline = in.readLine();
if (inline.equals("by")) {
break;
}
inline += "\n";
socket.getOutputStream().write(inline.getBytes());
socket.getOutputStream().flush();
}
}
public static class OutputThread extends Thread {
private InputStream inputstream;
public OutputThread(InputStream inputstream) {
this.inputstream = inputstream;
}
#Override
public void run() {
BufferedReader input = new BufferedReader(new InputStreamReader(inputstream));
while (true) {
try {
String line = input.readLine();
System.out.println(line);
} catch (IOException exception) {
exception.printStackTrace();
break;
}
}
}
}
}
I have server and client.
My server acepts all connections and returns to client string.
But when I try to send more lines its crashed with
java.net.SocketException: Socket is closed
at java.net.Socket.getOutputStream(Unknown Source)
at server.ServerCore.hiMsg(ServerCore.java:67)
at server.ServerCore.run(ServerCore.java:49)
Here is it my Server Code :
package server;
import java.io.File;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.*;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author pisio
*/
public class ServerCore extends Thread {
private LoadSettings loadSettings = LoadSettings.Init();
private int port = loadSettings.getConfigInt("port");
private int max_connections = loadSettings.getConfigInt("max_connections");
private String ipServer = loadSettings.getConfig("ipServer");
private ServerSocket socket;
private Socket connection;
private boolean serverRuning = false;
private int connectedUsers = 0;
private Vector connVector = new Vector();
#Override
public void run() {
try {
socket = new ServerSocket(port, max_connections);
System.out.println("+++\t Server was started at address:" + socket.getLocalSocketAddress() + " with posible max users " + max_connections);
serverRuning = true;
while (serverRuning) {
if (connectedUsers <= max_connections) {
connection = socket.accept();
connection.setKeepAlive(serverRuning);
connVector.add(connection);
connectedUsers = connVector.size();
hiMsg();
hiMsg();
hiMsg();
}
System.out.println("+++\t Last User:" + connVector.get(connVector.size() - 1).toString());
}
} catch (IOException ex) {
// Logger.getLogger(ServerCore.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void hiMsg() {
try {
Socket c = (Socket) connVector.get(connVector.size() - 1);
PrintWriter out = new PrintWriter(new OutputStreamWriter(c.getOutputStream()));
out.write("Hi user ! Im server ! Your master ! Blow me down\nping: ? PONG ?");
out.close();
} catch (IOException ex) {
Logger.getLogger(ServerCore.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void stopServer() {
statusServer();
serverRuning = false;
try {
socket.close();
} catch (IOException ex) {
//Logger.getLogger(ServerCore.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("+++++\t SERVER WAS STOPED !");
// System.exit(port);
}
public void statusServer() {
if (serverRuning) {
System.out.println("Server running at port:" + port + " with connected users :" + connectedUsers + "/" + max_connections);
} else {
System.out.println("Server IS NOT RUNNING!");
}
}
}
And Here is it my client code :
package meetingsclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.String;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ServerConnect {
private static ServerConnect sc = null;
private Socket socket = null;
private ServerConnect() {
try {
socket = new Socket("localhost", 8080);
sendHiMsg();
} catch (Exception ex) {
Logger.getLogger(ServerConnect.class.getName()).log(Level.SEVERE, null, ex);
}
}
private void sendHiMsg() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Input:" + in.readLine());
}
public static ServerConnect Init() {
if (sc == null) {
sc = new ServerConnect();
}
return ServerConnect.sc;
}
}
I readed this topic : Socket Exception: socket is closed but this dotn helped me.
// Sorry for the links , but I cant understand how properly to format my code here.
From the javadoc of getOutputStream() in Socket:
Closing the returned OutputStream will close the associated socket.
Also, closing a PrintWriter (and all other Printers/Writers) close their underlying streams as well. So, you are closing your OutputStream by closing the PrintWriter (in hiMsg()) and then trying to write to the socket, which was closed.
To fix the problem, don't close the PrintWriter. Garbage collection will take care of it for you! But do close the socket when you are done with it.