Error java.net.SocketException: Socket closed in Client-Server communication [duplicate] - java

This question already has an answer here:
java.net.SocketException: socket closed TCP Client Server Communication [duplicate]
(1 answer)
Closed 7 years ago.
I have a problem with the iterated transfer of ArrayList<Object> between client and server. Infact I have to receive in my client the List and the first time i try it works, but when i return in the program's Home interface and i retry to send the List it launch a java.net.SocketException: Socket closed. I think that my problem could probably be the erroneous closing of my data/object flux or the closing of the Sever Socket. Am i wrong?
Here is my Client code:
private final static int PORT = 6543;
Socket s = null;
DataInputStream in;
DataOutputStream out;
ObjectOutputStream outObj;
ObjectInputStream inObj;
private List<Comunication> pfList = new ArrayList<Comunication>();
public Socket Connect() throws IOException{
System.out.println("Provo a connettermi al server....");
s = new Socket("192.168.1.3",PORT);
System.out.println("Connesso.");
//in = new DataInputStream(s.getInputStream());
out = new DataOutputStream(s.getOutputStream());
inObj = new ObjectInputStream(s.getInputStream());
//outObj = new ObjectOutputStream(s.getOutputStream());
return s;
}
public void getZanzIn() throws IOException{
int i;
System.out.println("Entro in prova");
try {
System.out.println("Dentro prova prima del flusso");
pfList = (ArrayList<Comunication>)inObj.readObject();
System.out.println("Dentro prova dopo il flusso");
inObj.close();
//s.close();
} catch (IOException | ClassNotFoundException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
for (Communication pfList1 : pfList) {
System.out.println(pfList1.getIdOrdine()+ " " + pfList1.getNome() + " " + pfList1.getTipo() + " " + pfList1.getRiferimento()+" "+pfList1.getAltezza()+" "+pfList1.getLarghezza()+" "+pfList1.getTipoMisura()+" "+pfList1.getData()+" "+pfList1.getColore()+" "+pfList1.getAttaccoFrontale()+" "+pfList1.getFrizione()+" "+pfList1.getStatoTelaio()+" "+pfList1.getStatoRete()+" "+pfList1.getStatoLavorazione());
}
pfList.clear();
}
public void CommunicateServer () {
try {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str = "getZanzCut";
System.out.print(">> ");
out.writeUTF(str);
out.flush();
//str2=in.readUTF();
//System.out.println("Server says: "+str2);
out.close();
//s.close();
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
Here is the server code:
public class Server {
public final static int PORT = 6543;
ServerSocket ss = null;
Socket s = null;
DataInputStream in;
DataOutputStream out;
ObjectInputStream objIn;
ObjectOutputStream objOut;
Connection conn;
protected final static String NOMEDRIVER = "com.mysql.jdbc.Driver";
protected final static String SERVERURL = "jdbc:mysql://localhost:3306/datazanzariere?zeroDateTimeBehavior=convertToNull";
protected final static String USER = "root";
protected final static String PASSWORD = "admin";
public Socket WaitObj(){
try {
System.out.println("inizializzo il server");
ss = new ServerSocket(PORT);
System.out.println("server pronto in ascolto");
s = ss.accept();
System.out.println("connessione stabilita");
in = new DataInputStream(s.getInputStream());
objOut = new ObjectOutputStream(s.getOutputStream());
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
return s;
}
public void CommunicateClient(){
try {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str="";
str=in.readUTF();
System.out.println("client says: "+str);
System.out.print(":: ");
if(str.equals("getZanzCut")){
this.getZanzCut();
}
in.close();
//s.close();
//ss.close();
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void getZanzCut(){
try {
List<Comunication> comList = new ArrayList();
Class.forName(NOMEDRIVER);
conn = DriverManager.getConnection(SERVERURL, USER, PASSWORD);
Statement st = conn.createStatement();
Statement st2 = conn.createStatement();
Statement st3 = conn.createStatement();
Statement stm4 = conn.createStatement();
Statement stm5 = conn.createStatement();
st.execute("Create view Modello (ID, Tipo) as select ZanzarieraV, Tipo from verticale union all select Zanzariera, Tipo from laterale");
st2.execute("CREATE view DatiCliente (ID, Nome) as SELECT ClienteF, Cognome FROM personafisica UNION SELECT Cliente, NomeAzienda FROM personagiuridica");
ResultSet rs = st3.executeQuery("SELECT IdOrdine, D.Nome, Tipo, Riferimento, Larghezza, Altezza, TipoMisura, Data, C.Colore, Frizione, AttaccoFrontale\n" +
"FROM riepilogoordine R JOIN Colore C ON R.Colore = C.IdColore\n" +
"JOIN Modello M ON R.ZanzarieraO = M.ID \n" +
"JOIN DatiCliente D ON R.ClienteO = D.ID\n" +
"WHERE StatoRete = 'Da tagliare'");
while(rs.next()) {
Comunication com = new Comunication();
com.setIdOrdine(rs.getInt("IdOrdine"));
com.setNome(rs.getString("Nome"));
com.setTipo(rs.getString("Tipo"));
com.setRiferimento(rs.getString("Riferimento"));
com.setLarghezza(rs.getInt("Larghezza"));
com.setAltezza(rs.getInt("Altezza"));
com.setTipoMisura(rs.getString("TipoMisura"));
com.setData(rs.getDate("Data"));
com.setColore(rs.getString("Colore"));
com.setFrizione(rs.getString("Frizione"));
com.setAttaccoFrontale(rs.getString("AttaccoFrontale"));
comList.add(com);
}
objOut.writeObject(comList);
stm4.execute("drop view modello");
stm5.execute("drop view DatiCliente");
comList.clear();
conn.close();
objOut.close();
//s.close();
//ss.close();
} catch (ClassNotFoundException | SQLException | IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}

Closing the input stream or output stream of a socket closes the socket.
Solution: don't, until you're done with the socket.

Related

How to read or print the BufferedReader ( InputStreamReader)

I´m creating a new socket to send a string through the socket, then the socket generates a reply (I monitor the reply in Wireshark) but in the code I cannot see any answer, only if I connect again to the socket with another app, then I receive the answer in the first socket connection.
public class TCPConnections
{
public static void main (String[] args) throws Exception
{
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
String response = "";
String hostGreetings = "<frame><cmd><id>5</id><hostGreetings><readerType>SIMATIC_RF680R</readerType><supportedVersions><version>V2.0</version></supportedVersions></hostGreetings></cmd></frame>\n";
String getReaderStatus = "<frame><cmd><id>2</id><getReaderStatus></getReaderStatus></cmd></frame>\n";
StringBuilder antwort = new StringBuilder();
int c;
int counter = 0;
try
{
String host = "30S50RFID01.w30.bmwgroup.net";
int port = 10001;
InetAddress address = InetAddress.getByName(host);
System.out.println("adress: " + address);
socket = new Socket(address, port);
System.out.println("Socket connected: " + socket.isConnected());
System.out.println("Remote Port: " + socket.getPort());
System.out.println("Traffic Class: " + socket.getTrafficClass());
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
//byte [] bytes = hostGreetings.getBytes("UTF-8");
//System.out.println("UTF-8 = "+bytes);
if (socket.isConnected())
{
out.println(hostGreetings);
System.out.println("Message send:" + hostGreetings);
System.out.println("Message send:" + socket.getOutputStream());
System.out.println("Greeting sent, waiting for response");
Thread.sleep( 2000 );
boolean reading = true;
while (reading) {
if(in.ready ()){
c = (char) in.read();
response = response + c;
System.out.println("Reply" + response);
}else {
reading = false;
}
}
}
}
else
{
System.out.println("Socket connected: " + socket.isConnected());
}
}
catch (IOException ex)
{
System.out.println("Error 1: " + ex.getMessage());
}
catch (InterruptedException ex)
{
Logger.getLogger(TCPConnections.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{//Closing the socket
try
{
System.out.println("Connection will be closed and program terminated");
out.close();
in.close();
socket.close();
}
catch (IOException ex)
{
System.out.println("Error 2: " + ex.getMessage());
}
}
}
}`

Java socket client not connected to server

I get this error from my server when I call the the search animal's method. The
client connects to the server but as soon as I have clicked on the search method I get the following ERROR:
CONNECTED. getConnection
ServerConnect, searchAnimal: java.net.SocketException: Socket is not
connected
CONNECTED. getConnection
getConnection is the method to connect to database and sockets. I don't know how to fix it. Help please!
These are my declarations. I put the GUI and Server into one page of code:
public class MGLser5 extends JFrame { //declarations
static private JTextArea txtWin = new JTextArea();
private JScrollPane sp = new JScrollPane(txtWin);
private JButton clear = new JButton();
private int port;
Socket soc; //client socket
ServerSocket lstn; //server socket
InputStream in;
DataInputStream inData;
OutputStream out;
DataOutputStream outData;
static String client, username, password, request;
boolean connected;
static String model;
static Connection conn;
static Statement st;
static ResultSet rec;
private void startServer() {
try {
lstn = new ServerSocket(port);
txtWin.append("Listening on port number: " + port + "\n");
soc = lstn.accept();
connected = true;
in = soc.getInputStream();
inData = new DataInputStream(in);
out = soc.getOutputStream();
outData = new DataOutputStream(out);
//client = lstn.accept();
client = inData.readUTF();
txtWin.append("Connection established with " + client + "\n");
while (connected) {
model = "";
request = inData.readUTF();
txtWin.append("Request from client: \t" + request + "\n");
//db/socket disconnect
if ("Exit".equals(request)) {
try {
connected = false;
soc.close();
lstn.close();
in.close();
inData.close();
out.close();
outData.close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(MGLser5.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
delegate(request);
}
}
} catch (IOException ex) {
txtWin.append("Start Server 2: " + ex.getMessage() + "\n");
}
data base connection
public static void executeQ(String query) {
try {
connectDb();
st = conn.createStatement();
// Result set returned for a simple query
rec = st.executeQuery(query);
} catch (SQLException ex) {
txtWin.append("executeQ: " + ex.getMessage() + "\n");
}
}
constructor
public MGLser5(int portIn) {
super("Mokgele Game Lodge ");
port = portIn;
add("Center", sp);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(exitListener);
setSize(400, 300);
setVisible(true);
startServer();
}
search animal method
try {
String result = "";
while (connected) {
boolean match = Pattern.matches("[a-z]+", search);
if (!match || !"".equalsIgnoreCase(search)) {
connectDb();
java.sql.Statement stmt = conn.createStatement();
String sql1 = "SELECT * FROM Animals WHERE animal_name LIKE '%" + search + "%'";
String sql2 = "SELECT * FROM Species WHERE species_name LIKE '%" + search + "%'";
String sql3 = "SELECT Animal.* FROM Species INNER JOIN Animal ON Species.species_id = Animal.species_id WHERE (Species.species_name)=\'" + search + "\';";
ResultSet rs = stmt.executeQuery(sql1);
while (rs.next()) {
result += "\nAnimal ID: " + rs.getString(1) + "\nAnimal Name: " + rs.getString(2) + "\nInfo: " + rs.getString(3) + "\nSpecies ID: " + rs.getString(4);
result += "\n";
}
//If there's nothing in the Animal table, check the Species table
rs = stmt.executeQuery(sql2);
while (rs.next()) {
result += "\nID: " + rs.getString(1) + "\nSpecies Name: " + rs.getString(2);
result += "\n";
}
//Search for all the records of one classification, like all the felines or rodents
rs = stmt.executeQuery(sql3);
while (rs.next()) {
result += "\nAnimal ID: " + rs.getString(1) + "\nAnimal Name: " + rs.getString(2) + "\nInfo: " + rs.getString(3) + "\nSpecies ID: " + rs.getString(4);
result += "\n";
}
return result;
} else /*Error mssage for wrong search input*/ {
JOptionPane.showMessageDialog(null, "Error.\nPlease ReEnter your search agian");
return "";
}
}
return result;
} catch (SQLException e) {
System.out.println("Server, SearchAnimal: " + e);
connected = false;
return "";
}
Client server
//DECLARATIONS
private Socket clientSocket = new Socket();
private DataInputStream Datain;
private InputStream in;
private DataOutputStream Dataout;
private OutputStream out;
static private String server = "127.0.0.1", host;//local host
final int portIn = 8888;//port number
boolean isConnect = true;
public DataInputStream getInData() {
return Datain;
}
public DataOutputStream getOutData() {
return Dataout;
}
//CLIENT CONNECTIONS
public void getConnection() {
try {
//ServerSocket svrSoc = null;
clientSocket = new Socket(server, portIn);
//svrSoc = new ServerSocket(portIn);
//clientSocket = svrSoc.accept();
//Input stream from the server
in = clientSocket.getInputStream();
Datain = new DataInputStream(in);
//Output stream to the server
out = clientSocket.getOutputStream();
Dataout = new DataOutputStream(out);
Dataout.writeUTF(host);
System.out.println("CONNECTED. getConnection");
//closeConnection();
} catch (IOException e) {
System.out.println("ServerConnect, getConnection1: " + e);
//closeConnection();
} catch (NullPointerException e) {
System.out.println("ServerConnect, getConnection2: " + e);
//closeConnection();
}
}
private void getNewConnection(String request) {//send and receive data
try {
in = clientSocket.getInputStream();
Datain = new DataInputStream(in);
out = clientSocket.getOutputStream();
Dataout = new DataOutputStream(out);
host = request;
Dataout.writeUTF(host);
} catch (UnknownHostException ex) {
} catch (IOException ex) {
}
}
//Method to close the connection
public void closeConnection() {
try {
clientSocket.close();
Datain.close();
Dataout.close();
clientSocket.close();
System.out.println("DISCONNECTED .");
} catch (IOException e) {
System.out.println("ServerConnect, closeConnection: " + e);
} catch (NullPointerException e) {
System.out.println("ServerConnect, closeConnection: " + e);
}
}
//Method for Search method in Server
public String searchAnimal(String search) {
String fromServer;
try {
in = clientSocket.getInputStream();
Datain = new DataInputStream(in);
out = clientSocket.getOutputStream();
Dataout = new DataOutputStream(out);
if (isConnect) {
Dataout.writeUTF("searchAnimal");
Dataout.writeUTF(search);
fromServer = Datain.readUTF();
//closeConnection();
return fromServer;
} else {
System.out.println("ERROR SEARCH ANIMAL NOT FUNCTIONING ");
}
//closeConnection();
return "";
} catch (IOException e) {
System.out.println("ServerConnect, searchAnimal: " + e);
//closeConnection();
return "";
} catch (NullPointerException e) {
System.out.println("ServerConnect, searchAnimal: " + e);
//closeConnection();
return "";
}
}
private Socket clientSocket = new Socket();
The problem is here. You are creating an unconnected socket, which is pointless, and then never connecting it.

Chat Application in java

I'm trying to make a chat application in java, but I had a problem, when I couldn't send to another machine.
Here's part of my codes:
This is my class client:
public class EnvioSocket {
public static boolean enviarSocket(String nome, String ip, int porta,
String mensagem) {
String dados = nome + " : " + mensagem;
try {
Socket socket = new Socket(ip, porta);
OutputStream outToServer = socket.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF(dados);
out.close();
socket.close();
} catch (UnknownHostException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
return false;
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
return false;
}
return true;
}
}
This is my class server:
public class ServidorThread implements Runnable {
private JTextArea menssage;
public ServidorThread(JTextArea menssage) {
this.menssage = menssage;
}
#Override
public void run() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(Porta.PORTA);
while (true) {
Socket acceptedSocket = serverSocket.accept();
DataInputStream in = new DataInputStream(
acceptedSocket.getInputStream());
String menssage = in.readUTF();
this.menssage.append(DateUtils.dateToString(new Date(), "dd/MM/yyyy HH:mm") + " " + menssage + "\n");
in.close();
acceptedSocket.close();
}
} catch (IOException e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
}
}
define a port to socket
public final class Porta {
private Porta() {
}
public static final int PORTA = 6066;
}
I can only send a message to my own computer. How can I fix this?
I'm starting my thread inside of my class that make a GUI.
It looks like you've set up your Server right, but your client doesn't seem to ever connect to it. You need to create a socket which will connect to the server socket. This socket can then give you I/O streams to send data through.
Java's tutorial, complete with code examples
The question is not that simple to me...I can show you the basics for client server echo application in java...You can expand on that to make a chat session between to clients I suppose...here it goes...
public class MultiThreadServer implements Runnable {
Socket csocket;
private static boolean quitFlag = false;
MultiThreadServer(Socket csocket) {
this.csocket = csocket;
}
public static void main(String args[]) throws Exception {
ServerSocket ssock = new ServerSocket(1234);
System.out.println("Listening");
while (!quitFlag) {
Socket sock = ssock.accept();
System.out.println("Connected");
new Thread(new MultiThreadServer(sock)).start();
}
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(csocket.getInputStream()));
String action = in.readLine();
PrintStream pstream = new PrintStream(csocket.getOutputStream());
System.out.printf("Server received... " + action + " ...action\n");
switch (action) {
case "bottle":
for (int i = 3; i >= 0; i--) {
pstream.println("<p>" + i + " bottles of beer on the wall" + "</p>");
}
pstream.println("<p>" + action + "</p>");
break;
case "echo":
pstream.println("<p>" + action + "</p>");
break;
case "quit":
quitFlag = true;
break;
}
pstream.close();
csocket.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
Running the server to echo your response is easy...making the client or clients are more challenging...simple jsp Client..
<BODY>
<H1>Creating Client/Server Applications</H1>
<%
String serverInput = request.getParameter("serverInput");
//String serverInput = "bottle";
try{
int character;
Socket socket = new Socket("127.0.0.1", 1234);
InputStream inSocket = socket.getInputStream();
OutputStream outSocket = socket.getOutputStream();
String str = serverInput+"\n";
byte buffer[] = str.getBytes();
outSocket.write(buffer);
while ((character = inSocket.read()) != -1) {
out.print((char) character);
}
socket.close();
}
catch(java.net.ConnectException e){
%>
You must first start the server application
at the command prompt.
<%
}
%>
</BODY>
or better yet...
<body>
<%String name = request.getParameter("inputString");%>
<h1>Creating Client Applications</h1>
<p>Client Sent... <%=name%> ...to Server</p>
<%
//String serverInput = "bottle";
try{
int character;
Socket socket = new Socket("127.0.0.1", 1234);
OutputStream outSocket = socket.getOutputStream();
String str = name;
byte buffer[] = str.getBytes();
outSocket.write(buffer);
socket.close();
}
catch(java.net.ConnectException e){
%>
You must first start the server application
at the command prompt.
<%
}
%>
</body>

java [deprecation] readLine() in DataInputStream has been deprecated?

I wrote a java sever socket,it could connect postgresql and return values,but when I compile javac -deprecation SQLServer.java
And why warning cannot work?
It didn't have any error.How can I fix it?
SQLServer.java:66: warning: [deprecation] readLine() in DataInputStream has been deprecated
query = in.readLine();
^
1 warning
code:
import java.io.*;
import java.net.*;
import java.util.*;
import java.sql.*;
public class SQLServer extends Thread{
public static final int MYPORT = 6700;
ServerSocket listen_socket;
public SQLServer(){
try{
listen_socket = new ServerSocket (MYPORT);
}
catch(IOException e) {System.err.println(e);}
this.start();
}
public void run(){
try{
while(true)
{
Socket client_socket = listen_socket.accept();
SQLConnection c = new SQLConnection (client_socket);
}
}
catch(IOException e) {System.err.println(e);}
}
public static void main(String[] argv){
new SQLServer();
}
}
class SQLConnection extends Thread{
protected Socket client;
protected DataInputStream in;
protected PrintStream out;
protected String query;
public SQLConnection (Socket client_socket){
client = client_socket;
try{
in = new DataInputStream(client.getInputStream());
out = new PrintStream (client.getOutputStream());
}
catch(IOException e) {
System.err.println(e);
try {client.close();}
catch (IOException e2) {};
return;
}
this.start();
}
public void run(){
try{
query = in.readLine();
System.out.println("read query string <" + query + ">");
do_sql();
//out.println(d.toString());
}
catch (IOException e) {}
finally{
try {client.close();}
catch (IOException e) {};
}
}
public void do_sql(){
Connection con; // database connection object
Statement stmt; // SQL statement object
ResultSet rs; // SQL query results
ResultSetMetaData rsmd;
boolean more; // "more rows found" switch
String dsn = "jdbc:postgresql://localhost/postgres";
String user = "postgres";
String password = "123456";
String record;
int colcount, i;
try{
Class.forName ("org.postgresql.Driver");
con = DriverManager.getConnection(dsn, user, password);
stmt = con.createStatement();
rs = stmt.executeQuery(query);
more = rs.next();
if (!more) {
out.println("No rows found.");
return;
}
rsmd = rs.getMetaData();
colcount = rsmd.getColumnCount();
System.out.println(colcount + " columns in result set");
while (more) {
//build result string
record = "";
for (i=1; i <= colcount; i++){
record = record.concat(rs.getString(i) + " ");
}
out.println(record);
System.out.println(record);
more = rs.next();
}
rs.close();
stmt.close();
con.commit();
con.close();
}
catch (Exception e)
{
System.out.println("Exception occurred" + e.toString());
}
}
}
From DataInputStream#readLine javadoc:
Deprecated. This method does not properly convert bytes to characters. As of JDK 1.1, the preferred way to read lines of text is via the BufferedReader.readLine() method. Programs that use the DataInputStream class to read lines can be converted to use the BufferedReader class by replacing code of the form:
DataInputStream d = new DataInputStream(in);
with:
BufferedReader d = new BufferedReader(new InputStreamReader(in));
The method was deprecated because Streams are meant to be treating bytes, to treat text we have since a long time Readers & Writers as they offer the functionality to use encodings.
if you want text to be read try wrapping your stream into a reader
BufferedReader r = new BufferedReader(new InputStreamreader(your data stream, optional encoding parameter like "UTF-8"))
r.readLine();
This is what the Java API says:
Deprecated.
This method does not properly convert bytes to characters. As of JDK 1.1, the preferred way to read lines of text is via the BufferedReader.readLine() method. Programs that use the DataInputStream class to read lines can be converted to use the BufferedReader class by replacing code of the form:
DataInputStream d = new DataInputStream(in);
with:
BufferedReader d
= new BufferedReader(new InputStreamReader(in));

Read from mysql to client through server class

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();
}
}

Categories

Resources