So basically, what I'm trying to do is to read from my database MySQL through a server I have created. I put the info from my database in an ArrayList, but the client can't read it. When I add simple Strings, it works. But not when its from my database. Any solutions?
public class Server implements Runnable {
private ServerSocket server;
private Socket socket;
private ObjectOutputStream oos = null;
public Server() {
try {
server = new ServerSocket(4444);
new Thread(this).start();
} catch (Exception e) {
System.out.println(e);
}
}
public void run() {
System.out.println("Server running");
while (true) {
try {
socket = server.accept();
sayHi();
System.out.println("HallÄ");
} catch (Exception e) {
}
}
}
private void sayHi(){
DataOutputStream dos;
try {
dos = new DataOutputStream(socket.getOutputStream());
oos = new ObjectOutputStream(socket.getOutputStream());
dos.writeUTF("Hej");
sendNames();
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void sendNames() {
ArrayList<String> drinkar = new ArrayList<String>();
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "drycker";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "";
try{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url+db, user, pass);
try{
Statement st = (Statement) con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM drinktable");
while (res.next()) {
String s = res.getString("Name");
for(int i = 0; i<drinkar.size(); i++){
drinkar.add(s);
}
}
con.close();
}
catch (SQLException s){
System.out.println("SQL code does not execute.");
}
}
catch (Exception e){
e.printStackTrace();
}
ArrayList<String> a = new ArrayList<String>();
a.add("Hejsan");
a.add("Svejsan");
try {
FileOutputStream fos = new FileOutputStream("randomList");
oos = new ObjectOutputStream(fos);
oos.writeObject(drinkar);
oos.flush();
oos.reset();
oos.close();
fos.close();
} catch (Exception e) {
}
}
public static void main(String[] args) {
new Server();
}
}
public class Client implements Runnable {
private Socket socket;
private DataInputStream dis;
private ObjectInputStream ois = null;
public Client() {
socket = new Socket();
InetSocketAddress ipPort = new InetSocketAddress("192.168.0.10", 4444);
try {
socket.connect(ipPort);
dis = new DataInputStream(socket.getInputStream());
ois = new ObjectInputStream(socket.getInputStream());
} catch (Exception e) {
}
new Thread(this).start();
}
public void run() {
while (true) {
try {
String msg = dis.readUTF();
if (msg.equals("Hej")) {
Thread.sleep(50);
receiveArrayList();
}
} catch (Exception e) {
}
}
}
public void receiveArrayList() {
try {
FileInputStream fis = new FileInputStream("randomList");
ois = new ObjectInputStream(fis);
ArrayList<String> a= (ArrayList<String>) (ois.readObject());
for(int i = 0; i < a.size(); i++){
System.out.println((String)a.get(i));
}
ois.close();
} catch (ClassNotFoundException ex) {
System.out.println(ex);
} catch (IOException ex) {
System.out.println(ex);
}
}
public static void main(String[] args) {
new Client();
}
}
Related
when I try to send or receive a message with the sockets I can not do it, in java it tells me that the conecction was denied while in c# it tells me that the port is already being used, in java I send my message by clicking a button and I receive it with a thread and in a similar way in c#, I would really appreciate if you could tell me what is wrong, I have tried everything but I can not find the answer, thanks.
Java
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
String mensaje = jTextField1.getText();
System.out.println(mensaje);
byte men[] = mensaje.getBytes();
Socket socket = null;
ObjectOutputStream out = null;
try {
socket = new Socket("127.0.0.1", 7000);
out = new ObjectOutputStream(socket.getOutputStream());
out.write(men, 0, men.length);
out.close();
socket.close();;
} catch (Exception e) {
e.printStackTrace();
}
}
class HiloReceptor extends Thread {
#Override
public void run() {
super.run();
while (true) {
try {
ServerSocket ss = new ServerSocket(7000);
Socket socketCanal = ss.accept();
ObjectInputStream ois = new ObjectInputStream(socketCanal.getInputStream());
byte[] mensaje = new byte[1024];
ois.read(mensaje, 0, mensaje.length);
String msgRecibido = new String(mensaje, 0 ,mensaje.length);
System.out.println(msgRecibido);
jLabel1.setText("Mensaje recibido: " + msgRecibido);
ois.close();
socketCanal.close();
ss.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
C#
private void button1_Click(object sender, EventArgs e)
{
try
{
String mensaje = textBox1.Text;
Console.WriteLine(mensaje);
byte[] men = UTF8Encoding.UTF8.GetBytes(mensaje);
IPAddress ip = IPAddress.Parse("127.0.0.1");
IPEndPoint endp = new IPEndPoint(ip, 7000);
TcpListener tcpListener = new TcpListener(endp);
tcpListener.Start();
//Socket socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
Socket socket = tcpListener.AcceptSocket();
//socket.Connect(endp);
socket.Send(men, men.Length, 0);
socket.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error al enviar.\n" + ex);
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
while (!backgroundWorker1.CancellationPending)
{
try
{
Console.WriteLine("entre al ciclo");
IPAddress ip = IPAddress.Parse("127.0.0.1");
IPEndPoint endp = new IPEndPoint(ip, 7000);
Socket s = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
s.Bind(endp);
s.Listen(1);
Socket canal = s.Accept();
byte[] buffer = new byte[1024];
msg = "";
while (canal.Receive(buffer, buffer.Length, 0) > 0)
{
msg += Encoding.UTF8.GetString(buffer);
}
Console.WriteLine(msg);
backgroundWorker1.ReportProgress(1);
canal.Close();
s.Close();
}
catch (Exception ex)
{
Console.WriteLine("Error.\n"+ ex);
}
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.ProgressPercentage == 1)
{
label1.Text = "Mensaje recibido: " + msg;
}
}
It's my first time working with sockets, in order to get a better understanding of what's going on I decided to build a client server chat application which can support several users.
At first, I used DataInputStream / DataOutputStream to communicate and everything works well. But I would like to switch to an ObjectStream and that's where the problem occurs. Once I replace all the DataInputStream / DataOutputStream by ObjectInputStream / ObjectOutputStream, I'm no longer able to print the retrieved data.
This is the code that I used before, which works (DataStream) :
SERVER:
try {
DataInputStream in = new DataInputStream(socket.getInputStream());
DataOutputStream out = new DataOutputStream(socket.getOutputStream());
out.writeUTF("HI FROM SERVER");
while (!socket.isClosed()) {
try {
if (in.available() > 0) {
String input = in.readUTF();
for (ClientThread thatClient : server.getClients()){
DataOutputStream outputParticularClient = new DataOutputStream(thatClient.getSocket().getOutputStream());
outputParticularClient.writeUTF(input + " GOT FROM SERVER");
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
CLIENT:
try {
socket = new Socket("localhost", portNumber);
DataInputStream in = new DataInputStream(socket.getInputStream());
new Thread(()->{
while(!socket.isClosed()){
try {
if (in.available() > 0){
String input = in.readUTF();
System.out.println(getUserName() + " > " + input);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
And this is how I tried to perform the same idea with ObjectStream :
SERVER:
try {
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
while (!socket.isClosed()) {
try {
if (in.available() > 0) {
Message input;
try {
input = (Message)in.readObject();
if (input.equals(null)){
System.err.println("SERVER RETRIEVED NULL OBJECT");
}
for (ClientThread thatClient : server.getClients()){
ObjectOutputStream outputParticularClient = new ObjectOutputStream(thatClient.getSocket().getOutputStream());
outputParticularClient.writeObject(input);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
CLIENT:
try {
socket = new Socket(getHost(), portNumber);
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
new Thread(()->{
while(!socket.isClosed()){
try {
if (in.available() > 0){
Message input = null;
try {
input = (Message)in.readObject();
if (input.equals(null)){
System.err.println("CLIENT RETRIEVED NULL OBJECT");
}
System.out.println("CLIENT " + input.toString());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
I feel like it has something to do with this if statement if (in.available() > 0) but I cannot say precisely what's going on.
available() doesn't do what you may think it does and it is almost never useful in production code (and that's particularly true for ObjectInputStream). The reason you don't receive any data is in fact that in.available() always returns 0 as you already suspected.
As noted in the comments, the StreamCorruptedException is caused by writing to an existing ObjectInputStream that has already been written to using another instance of ObjectOutputStream. Cf. the answer StreamCorruptedException: invalid type code: AC for further explanation.
Here is some quick & dirty example code that has a server echoing the messages from two clients. It's not clean but it may give you an idea how to approach your problem:
public class SO56493162 {
private static final class Message implements Serializable {
private static final long serialVersionUID = 1L;
private static int cnt = 0;
private final int id;
public Message(int id) {
++cnt;
this.id = id;
}
public String toString() {
return "Msg from " + id + " : " + cnt;
}
}
private static final class Client implements Runnable {
private InetSocketAddress addr = null;
private int id = -1;
Client(InetSocketAddress addr, int id) {
this.addr = addr;
this.id = id;
}
public void run() {
int timeout = 3000;
Socket s = null;
try {
s = new Socket();
s.connect(addr, timeout);
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
System.out.println("Client " + id + " connected");
while (true) {
Thread.sleep(new Random().nextInt(2000));
Message hello = new Message(id);
oos.writeObject(hello);
oos.flush();
Message reply = (Message) ois.readObject();
System.out.println("Reply: " + reply.toString());
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
s.close();
} catch (Exception ignore) {
}
}
}
}
private static final class Server implements Runnable {
private ServerSocket sock = null;
Server(ServerSocket sock) throws IOException {
this.sock = sock;
}
public void run() {
System.out.println("starting server");
try {
while (true) {
final Socket client = sock.accept();
System.out.println("connection accepted");
Thread t = new Thread(new Runnable() {
#Override
public void run() {
try {
ObjectInputStream ois = new ObjectInputStream(client.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(client.getOutputStream());
while (!client.isClosed()) {
try {
Message input = (Message) ois.readObject();
oos.writeObject(input);
oos.flush();
} catch (EOFException eof) {
System.err.println("EOF!");
client.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
t.setDaemon(true);
t.start();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String args[]) throws IOException, InterruptedException {
final int port = 9876;
Thread ts = new Thread(new Runnable() {
#Override
public void run() {
try {
new Server(new ServerSocket(port)).run();
} catch (Exception e) {
e.printStackTrace();
}
}
});
ts.setDaemon(true);
ts.start();
InetSocketAddress addr = new InetSocketAddress("localhost", port);
for (int i = 0; i < 2; ++i) {
Client cl = new Client(addr, i);
Thread tc = new Thread(cl);
tc.setDaemon(true);
tc.start();
}
Thread.sleep(10000);
System.err.println("done");
}
}
I am having trouble making a multi client server for a game that i have made. I am able to create a ServerSocket, make a connection and send data through means of a ObjectInputStream and ObjectOutputStream. My problems lies when it comes to multiple clients, from what i understand a new thread needs to be created for each client but the data i would like to send and receive is hard coded into the client class. How would I allow my Client to send changeable data?
Here is my client class:
public class Client extends Thread {
private Server server = new Server();
private Socket connection;
private ObjectOutputStream out;
private ObjectInputStream in;
public Client(Socket connection) {
this.connection = connection;
this.out = server.objOutStream(this.connection);
this.in = server.objInStream(this.connection);
}
public void run() {
while(this.connection.isConnected()) {
//
List<String> list = new ArrayList<String>();
list.add("hello there");
server.sendData(out, list);
//
List<String> recive = new ArrayList<String>();
recive = server.reveiveData(in);
}
}
public Socket getConnection() {
return connection;
}
}
and Here is the server side:
public ServerSocket createServer(Integer serverPort, Integer serverSize) {
ServerSocket server = null;
try {
server = new ServerSocket(serverPort, serverSize);
System.out.println("created server");
} catch (IOException e) {
e.printStackTrace();
}
return server;
}
public Socket makeConnection(ServerSocket server) {
Socket connection = null;
try {
connection = server.accept();
Client client = new Client(connection);
client.start();
System.out.println("connection made with " + connection.getInetAddress().getHostAddress());
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
public ObjectInputStream objInStream(Socket connection) {
ObjectInputStream in = null;
try {
in = new ObjectInputStream(connection.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
return in;
}
public ObjectOutputStream objOutStream(Socket connection) {
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(connection.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
return out;
}
public void sendData(ObjectOutputStream out, List<String> list) {
try {
out.writeObject(list);
out.flush();
System.out.println("sending " + list);
} catch (IOException e) {
e.printStackTrace();
}
}
public List<String> reveiveData(ObjectInputStream in) {
List<String> list = null;
try {
list = (List<String>) in.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
return list;
}
public Socket joinServer(String serverIP, Integer serverPort) {
Socket connection = null;
try {
connection = new Socket(InetAddress.getByName(serverIP), serverPort); System.out.println("joined");
} catch (IOException e) {
e.printStackTrace();
}
return connection;
}
public void stop(Socket connection) {
System.out.println("closing");
try {
if(connection.isInputShutdown() == false) {
connection.getInputStream().close();
}
if(connection.isOutputShutdown() == false) {
connection.getOutputStream().close();
}
if(connection.isConnected() == true) {
connection.close();
}
System.exit(0);
} catch (IOException e) {
e.printStackTrace();
}
}
In my mian class I run this:
try {
if(connection == null) {
connection = server.makeConnection(serverSocket);
in = server.objInStream(connection);
out = server.objOutStream(connection);
}else {
//readlist
List<String> readList = (List<String>) in.readObject();
System.out.println("reciving: " + readList);
//writelist
List<String> writeList = new ArrayList<String>();
writeList.add("hi");
out.writeObject(writeList);
System.out.println("sending: " + writeList);
}
}catch(IOException | ClassNotFoundException e) {
e.printStackTrace();
}
I am getting the broken pipe error while the client stopping the build process and new client connect with server and sending message to the server.
Here my Server code:
public class Server {
ArrayList<ObjectOutputStream> ListOfclientOutputStreams;
public Server() {
ListOfclientOutputStreams = new ArrayList<ObjectOutputStream>();
try {
ServerSocket serverSocket = new ServerSocket(7503);
while(true) {
Socket serverCommunicationSocket;
serverCommunicationSocket = serverSocket.accept();
ObjectOutputStream eachClientobjectOutStream = new ObjectOutputStream(serverCommunicationSocket.getOutputStream());
ListOfclientOutputStreams.add(eachClientobjectOutStream);
Thread threadForSpecificClient = new Thread(new SpecificClient(serverCommunicationSocket));
threadForSpecificClient.start();
System.out.println("Got a connection");
}
}catch(IOException ex) {
ex.printStackTrace();
}
}
private class SpecificClient implements Runnable {
private ObjectInputStream eachClientObjectInputStream;
private Socket sock;
public SpecificClient(Socket specificSocket) {
try {
sock = specificSocket;
eachClientObjectInputStream = new ObjectInputStream(sock.getInputStream());
}catch (IOException ex) {
ex.printStackTrace();
}
}
public void run() {
Message msgObject;
try {
while((msgObject = (Message) eachClientObjectInputStream.readObject()) !=null) {
System.out.println("Client thread on the server read" + msgObject);
broadCast(msgObject);
}
}catch (IOException ex) {
ex.printStackTrace();
}catch(ClassNotFoundException ex){
System.out.println("Unable to read the message object in server");
ex.printStackTrace();
}
}
public void broadCast(Message msgObject) {
Iterator<ObjectOutputStream> iter = ListOfclientOutputStreams.iterator();
try {
while(iter.hasNext()) {
ObjectOutputStream out = iter.next();
out.writeObject(msgObject);
out.flush();
}
}catch(IOException ex) {
System.out.println("Unable to add the Message object to the outputstream in the server");
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
Server server1 = new Server();
}
}
This is my client coding:
public class Client {
private ObjectOutputStream clientOutStream;
private ObjectInputStream clientInStream;
private Socket clientSocket;
public Client() throws InterruptedException {
establishConnection();
createStreams();
Thread threadToRead = new Thread(new Incoming());
threadToRead.start();
}
public void establishConnection() {
try {
int port = Integer.parseInt(Session.port);
clientSocket = new Socket("127.0.0.1", port);
System.out.println("Network connection Established");
}catch (IOException ex) {
ex.printStackTrace();
}
}
public void createStreams() {
try {
clientInStream = new ObjectInputStream(clientSocket.getInputStream());
clientOutStream = new ObjectOutputStream(clientSocket.getOutputStream());
System.out.println("Connection streams established");
}catch (IOException ex) {
ex.printStackTrace();
}
}
private class Incoming implements Runnable {
public void run() {
String personIn;
Message msgObject = new Message();
try
{
personIn=personLoggedIn.getText().toString();
while((msgObject= (Message) clientInStream.readObject()) !=null)
{
//updateWhoIsOnline();
System.out.println("Client is Reading the object from the server");
String postedTo = msgObject.getPostedTo().replace(",", "").replace("[", "").replace("]", "");
System.out.println("Posted To : "+postedTo);
String[] result = postedTo.split(" ");
int len = result.length;
System.out.println("Length : "+len);
System.out.println("First string : "+result[0].toString());
//System.out.println("Second string : "+result[1].toString());
for(int i=0;i<len;i++) {
if(result[i].toString().equals("All") || result[i].toString().equals(personIn) || msgObject.getPostedBy().equals(personIn)) {
chatDetailsViewArea.append(msgObject.getPostedBy() + " ->" + result[i].toString() + ":" + msgObject.getContent() + "\n");
}
}
}
}
catch(IOException ex)
{
System.out.println("Error in figuring out who to post the message to");
ex.printStackTrace();
}
catch(ClassNotFoundException ex)
{
ex.printStackTrace();
}
}
}
}
How do I create a .ser file or write objects to a .ser file in a localhost server?
The following code can read .ser file :
public Object deserialize(InputStream is) {
ObjectInputStream in;
Object obj;
try {
in = new ObjectInputStream(is);
obj = in.readObject();
in.close();
return obj;
} catch (IOException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
}
URL url;
URLConnection urlConn;
DataInputStream dis;
//url = new URL("http://localhost/Person.ser");
urlConn = url.openConnection();
urlConn.setDoInput(true);
urlConn.setUseCaches(false);
Person person = (person) deserialize(urlConn.getInputStream());
Do I need any server side program to receive the object and store in the file?
you can write to .ser file using following way:
try {
FileOutputStream fos = new FileOutputStream("Filename.ser");
ObjectOutputStream out = new ObjectOutputStream(fos);
out.write(obj);
fos.close();
out.close();
} catch (IOException ex) {}
UPDATE
To read the object at server side you need to create ObjectInputStream wrappint the inputStream of socket via which it is interacting with client . It can be done as follows:
try
{
Socket s = serverSocket.accept();
ObjectInputStream oin = new ObjectInputStream(s.getInputStream());
Object obj = oin.readObject();
oin.close();
}catch(Exception ex){}
OK here is the complete example where I am sending an ArrayList to Server.
Client.java
import java.net.*;
import java.io.*;
import java.util.*;
public class Client
{
public static void main(String[] args)
{
Socket s = null;
ObjectOutputStream out = null;
System.out.println("Connecting to Server ...");
try
{
s = new Socket("localhost", 1401);
out = new ObjectOutputStream (s.getOutputStream());
ArrayList<String> list = ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < 10 ; i++)
{
list.add("String"+i);
}
out.writeObject(list);out.flush();
System.out.println("ArrayList sent to Server");
} catch ( Exception e)
{
e.printStackTrace();
}
finally
{
if (out!= null)
{
try
{
out.close();
}
catch (Exception ex){}
}
if (s != null)
{
try
{
s.close();
}
catch (Exception ex){}
}
}
}
}
Server.java
import java.net.*;
import java.io.*;
import java.util.*;
public class Server
{
public static void main(String[] args)
{
ObjectInputStream oin = null;
ServerSocket server;
Socket socket = null;
try
{
server = new ServerSocket(1401);
socket = server.accept();
System.out.println("Client Connected..Sending ArrayList to Client");
oin = new ObjectInputStream(socket.getInputStream());
ArrayList<String> list = (ArrayList<String>)oin.readObject();
System.out.println("Recieved ArrayList from client "+list);
//Writing to file now
FileOutputStream fos = new FileOutputStream("Filename.ser");
ObjectOutputStream out = new ObjectOutputStream(fos);
out.write(obj);
fos.close();
out.close();
System.out.println("Written to file");
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if (oin != null)
{
try
{
oin.close();
}
catch (Exception ex){}
}
if (socket != null)
{
try
{
socket.close();
}
catch (Exception ex){}
}
}
}
}