Im trying to make a basic email system in Java. I have a server that the clients connect to and a gui for the clients. When the server picks up a new connection from a client it starts a new thread running that handles all the different operations. The problem is that the server accepts the new client but doesnt start a new client handler thread running. Any help?
public class Server {
public static Connection link;
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
final int PORT = 1234; // Define the sockets and ports and i/o
Socket client;
ClientHandler handler;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
link = DriverManager.getConnection("jdbc:odbc:emails", "", "");
System.out.println("Connected to Database . . . ");
} catch (ClassNotFoundException cnfEx) {
System.out.println("* Unable to load driver! *");
System.exit(1);
} catch (SQLException sqlEx) {
System.out.println("* Cannot connect to database! *");
System.exit(1);
}
try {
serverSocket = new ServerSocket(PORT); // Set the server socket
} catch (IOException ioEx) {
System.out.println("\nUnable to set up port!"); // If failed let the
// user know
System.exit(1); // Exit the system with error code 1
}
System.out.println("\nServer running...\n"); // Tell the user the server
// is running
do {
client = serverSocket.accept();
// Wait for client.
System.out.println(client);
handler = new ClientHandler(client);
System.out.println(handler);
System.out.println("\nNew client accepted.\n"); // Tell the user the
// server has accepted
// a client
System.out.println("RUNNING");
handler.start(); // Start the handler
} while (true); // Continuous loop
}
static class ClientHandler extends Thread {
/**
*
*/
private Socket client;
private ObjectInputStream input; // Define sockets, i/o and local array
// list
private ObjectOutputStream output;
public ClientHandler(Socket socket) throws IOException // Client handler
// constructor
{
client = socket;
input = new ObjectInputStream(socket.getInputStream());// Set client
// and i/o
// stream
output = new ObjectOutputStream(socket.getOutputStream());
}
public void run() {
String userCommand = null;
System.out.println("RUNNING CLIENT HANDLER");
boolean quit = false;
do {
try {
userCommand = (String) input.readObject();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (ClassNotFoundException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} // Receive user command
if (userCommand.equals("SEND MESSAGE")) // If user command is to
// send a message
{
String username = null, recipient = null, message = null, insert, fileType = null;
try {
username = (String) input.readObject();
recipient = (String) input.readObject(); // Receive username,
// recipient and
// message
message = (String) input.readObject();
fileType = (String) input.readObject();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
insert = "INSERT INTO [emails] ([From], [To], [Message], [Attachment])"
+ " VALUES('"
+ username
+ "','"
+ recipient
+ "','"
+ message + "','" + fileType + "')";
Statement statement = null;
try {
statement = link.createStatement();
statement.executeUpdate(insert);
link.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
getFile(input, fileType);
} catch (IOException ioEx) {
ioEx.printStackTrace();
} catch (ClassNotFoundException cnfEx) {
cnfEx.printStackTrace();
}
System.out.println(username // Tell the user a message has been
// sent
+ " sent message to " + recipient);
}
if (userCommand.equals("READ MESSAGE")) // If user command is to
// read a message
{
String username = null; // Define local variables
try {
username = (String) input.readObject();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} // Receive the username of the current user
Statement statement = null;
String insert = "SELECT [Email No],[From],[Message],[Attachment] FROM [emails] WHERE To = '"
+ username + "'";
ResultSet rs = null;
try {
statement = link.createStatement();
rs = statement.executeQuery(insert);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while (rs.next()) {
String from = rs.getString("From");
String message = rs.getString("Message");
String attachment = rs.getString("Attachment");
int emailNo = rs.getInt("Email no");
output.writeObject(from);
output.writeObject(message); // Send the username the
// message is from
output.writeObject(attachment);
output.writeObject(emailNo);
output.flush(); // and the message and flush the output
// stream
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
output.writeObject("END");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // Send an end message
try {
output.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // Flush the output stream
System.out.println(username // Tell the user someone is reading
// their messages
+ " reading messages.");
}
if (userCommand.equals("QUIT")) // If the user command is quit
{
quit = true; // Set quit to true
}
if (userCommand.equals("DELETE MESSAGE")) // If the user command is
// delete a message
{
int valueToDelete = 0; // Define local variables
try {
valueToDelete = Integer.parseInt((String) input.readObject());
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} // Receive the value to delete
Statement statement = null;
String delete = "DELETE FROM emails WHERE [Email No] = "
+ valueToDelete + "";
try {
statement = link.createStatement();
statement.executeUpdate(delete);
link.commit();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Deleted message " + valueToDelete); // Tell
// the
// user a
// message
// has
// been
// deleted
}
} while (!quit); // Run while quit is false
System.out.println("Client Closed"); // Tell the user the client has // closed
}
private static void getFile(ObjectInputStream inStream, String fileType)
throws IOException, ClassNotFoundException {
byte[] byteArray = (byte[]) inStream.readObject();
FileOutputStream mediaStream = null;
if (fileType.equals("Text File"))
mediaStream = new FileOutputStream("file.txt");
else if (fileType.equals("Image"))
mediaStream = new FileOutputStream("file.gif");
else if (fileType.equals("Movie"))
mediaStream = new FileOutputStream("file.mpeg");
mediaStream.write(byteArray);
}
}
}
When you are instantiating the ObjectInputStream it will block until the client sends a sufficient header, thus you never get to actually run the thread... See also
Related
I have created a program to convert text to xml by using ReverseXSL API.
This program is to be executed by an application by calling static method (static int transformXSL).
I am able to execute and produce output with running from Eclipse. However, When I ran program (jar) by using application it stuck somewhere and I couldnt find anything.
Then, I debugged by "Debug as...-> Remote Java Application" in Eclipse from Application and found "InvocationTargetException" at ClassLoaders.callStaticFunction.
Below Static method is called by application.
public class MyTest4 {
public MyTest4()
{
}
public static int transformXSL(String defFile, String inputFile, String XSLFile, String OutputFile) {
System.out.println("Dheeraj's method is called");
// start time
FileWriter fw=null;
try {
fw = new FileWriter("D://Countime.txt");
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
BufferedWriter output=new BufferedWriter(fw);
DateFormat sd=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Date dt= new Date();
System.out.println("Date is calculated");
try {
output.write("Start Time:"+sd.format(dt).toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(sd.format(dt));
FileReader myDEFReader=null, myXSLReader=null;
TransformerFactory tf = TransformerFactory.newInstance();
Transformer t=null;
FileInputStream inStream = null;
ByteArrayOutputStream outStream = null;
// Step 1:
//instantiate a transformer with the specified DEF and XSLT
if (new File(defFile).canRead())
{
try {
myDEFReader = new FileReader(defFile);
System.out.println("Definition file is read");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else myDEFReader = null;
if (new File(XSLFile).canRead())
try {
myXSLReader = new FileReader(XSLFile);
System.out.println("XSL file is read");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
else myXSLReader = null;
try {
t = tf.newTransformer(myDEFReader, myXSLReader);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Step 1: DEF AND XSLT Transformation completed");
// Step 2:
// Read Input data
try {
inStream = new FileInputStream(inputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
outStream = new ByteArrayOutputStream();
System.out.println("Step 2: Reading Input file: completed");
// Step 3:
// Transform Input
try {
try (BufferedReader br = new BufferedReader(new FileReader("D://2.txt"))) {
String line = null;
while ((line = br.readLine()) != null) {
System.out.println("Content: "+line);
}
}
System.out.println("File: "+inputFile.toString());
System.out.println("\n content: \n"+ inStream.toString());
System.out.println("Calling Transform Function");
t.transform(inStream, outStream);
System.out.println("Transformation is called");
outStream.close();
try(OutputStream outputStream = new FileOutputStream(OutputFile)) {
outStream.writeTo(outputStream);
System.out.println("Outstream is generated; Output file is creating");
}
System.out.println(outStream.toString());
} catch (TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (TransformerFactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (javax.xml.transform.TransformerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("output file is created");
// End time
Date dt2= new Date();
System.out.println(sd.format(dt2));
System.out.println("End time:"+dt2.toString());
try {
output.append("End Time:"+sd.format(dt2).toString());
output.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
}
I am developping an Android app and a java desktop app. The Android app send to the java desktop the sms received, and the desktop app provide an interface for answering to these sms.
The android app is the server, the desktop app connects to it through a socket.
Here is the code of the server (android app side)
public class Server extends AsyncTask<Void, Void, Void> {
public void stopServ(){
this.run=false;
}
public void newSMSReceived(String sms, String phone){
//SEND THE NEW SMS TO THE DESKTOP APP
try {
outputStream.writeUTF(new String(sms.getBytes(),"ISO-8859-1"));
outputStream.flush();
outputStream.writeUTF(new String(phone.getBytes(),"ISO-8859-1"));
outputStream.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected Void doInBackground(Void... params) {
ServerSocket ss = null;
try {
ss = new ServerSocket(TCP_SERVER_PORT);
Socket s = ss.accept();
System.out.println("connection received !");
inputStream = new ObjectInputStream(s.getInputStream());
outputStream = new ObjectOutputStream(s.getOutputStream());
outputStream.writeObject(contacts);
outputStream.flush();
while(true){
//READ THE MESSAGE SENDED FROM THE DESKTOP APP
message=inputStream.readUTF();
phone=inputStream.readUTF();
smsManager.sendTextMessage(phone.replaceFirst("0", "\\+33"), null, message, null, null);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
}
The desktop app side :
public class Main extends Application {
public Main(){
try {
PropertiesRetriever prop = new PropertiesRetriever();
socket = new Socket(prop.getIp(), 5657);
outputStream = new ObjectOutputStream(socket.getOutputStream());
inputStream = new ObjectInputStream(socket.getInputStream());
Thread listener = new Thread(new Runnable() {
public void run() {
while(true){
String message,phone;
Contact contact;
try {
//RECEIVED THE MESSAGE FROM THE ANDROID APP
message=inputStream.readUTF();<--- EOFException
phone=inputStream.readUTF();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
listener.start();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public void sendMessage(Contact contact, Message message){
try {
//SEND THE MESSAGE TO THE ANDROID APP
outputStream.writeUTF(message.getTextUTF());
outputStream.flush();
outputStream.writeUTF(contact.getPhoneUTF());
outputStream.flush();
System.out.println(message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**...**/
}
The details of the method "getxxUTF":
String rtr=null;
try {
rtr = new String(text.getBytes(),"ISO-8859-1");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return rtr;
EOFException :
java.io.EOFException
at java.io.DataInputStream.readUnsignedShort(DataInputStream.java:340)
at java.io.ObjectInputStream$BlockDataInputStream.readUnsignedShort(ObjectInputStream.java:2818)
at java.io.ObjectInputStream$BlockDataInputStream.readUTF(ObjectInputStream.java:2874)
at java.io.ObjectInputStream.readUTF(ObjectInputStream.java:1073)
Thing is, at a point, I get an EOFException on the readUTF mentioned above. Everything works fine until a certain point, and I have no clue why... Someone ?
You get this not 'randomly' but when the peer has closed the connection.
I have simple client and server, the client is based on NIO where as the server is a simple old style program.
I am using the client in its default mode which is blocking. In the program i try to write from the client side, server reads it. Then server replies and the client reads it.
I am able to write into the server with no issues, but the read from the Server in the client is proving to be problematic. As it is in blocking mode, i expect that it never returns 0 according to the documentation. But thats not what is happening, i always see the return from client_channel.read as 0.
*******************************SERVER*******************************************
class MyBlockingServer extends Thread
{
private int M_PortNumber;
private ServerSocket M_ServerSocket;
MyBlockingServer(int PortNumber)
{
M_PortNumber = PortNumber;
try {
M_ServerSocket = new ServerSocket(M_PortNumber);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void run()
{
int my_number = 0;
while(true)
{
try {
Socket ClientServerTuple = M_ServerSocket.accept();
//System.out.println("Server address is "+ ClientServerTuple.getLocalAddress() + "Server Port is " + ClientServerTuple.getLocalPort());
//System.out.println("Client address is " + ClientServerTuple.getRemoteSocketAddress() + "Client address is" + ClientServerTuple.getPort());
DataInputStream inputStream = new DataInputStream(ClientServerTuple.getInputStream());
byte b[] = new byte[48];
inputStream.read(b);
System.out.println("[SERVER]" + new String(b));
DataOutputStream outputStream = new DataOutputStream(ClientServerTuple.getOutputStream());
byte c[] = new byte[100];
String output= new String("Thanks for connection, you suck tata" + " "+ my_number);
c = output.getBytes();
outputStream.write(c);
my_number++;
System.out.println("write done");
ClientServerTuple.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
void socket_close()
{
try {
M_ServerSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class JavaBlocking
{
public static void main(String []args)
{
MyBlockingServer Server = new MyBlockingServer(8000);
try {
Server.start();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
*******************************CLIENT*******************************************
public class JavaChannels
{
public static void main(String []args)
{
SocketChannel client_channel = null;
try {
client_channel = SocketChannel.open();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("[Async Client] Socket channel open");
try {
client_channel.connect(new InetSocketAddress("127.0.0.1",8000));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("[Async Client] Socket channel connected");
ByteBuffer my_buffer = ByteBuffer.allocate(248);
try {
my_buffer.put("seven77".getBytes("UTF-8"));
} catch (UnsupportedEncodingException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
my_buffer.flip();
try {
int bytes_written = client_channel.write(my_buffer);
while(my_buffer.hasRemaining())
{
bytes_written = client_channel.write(my_buffer);
}
System.out.println("[Async Client] Wrote "+ bytes_written +" bytes");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("[Async Client] Socket channel write finished");
my_buffer.clear();
my_buffer.flip();
try {
int read_length = client_channel.read(my_buffer);
System.out.println("Initial read is " + read_length + " bytes");
while(read_length !=-1)
{
read_length = client_channel.read(my_buffer);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Reading the buffer." +"Read "+read_length +"bytes");
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
System.out.println("[Async Client] server says" + new String(my_buffer.array()));
try {
client_channel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The output i am seeing from the client side is as follows
Initial read is 0 bytes
Reading the buffer.Read 0bytes
Reading the buffer.Read 0bytes
Reading the buffer.Read 0bytes
I think that this is wrong:
System.out.println("[Async Client] Socket channel write finished");
my_buffer.clear();
my_buffer.flip();
The clear prepares the buffer for reading by setting the position to zero and the limit to the capacity.
But the flip then sets the limit to the position; i.e. zero. That means than when you attempt to read into the buffer, there is space for zero bytes.
Get rid of that flip call.
As it is in blocking mode, i expect that it never returns 0 according to the documentation.
Which documentation? The javadocs for SocketChannel.read(ByteBuffer) says:
"It is guaranteed, however, that if a channel is in blocking mode and there is at least one byte remaining in the buffer then this method will block until at least one byte is read. "
In this case, the highlighted condition is false.
While connecting to a URL i'm getting Below is the logcat error i'm getting
and below that my code to connect to url.
When i try to connect to base url http://www.apkmania.co/ it connects successfully
but when try to connect to this url it throws me an error.
07-31 20:47:20.150: I/System.out(14295): IOException: org.jsoup.HttpStatusException: HTTP error fetching URL. Status=404, URL=http://www.apkmania.co/2013/07/blood-sword-thd-v16-apk.html/
break;
Thread thread=new Thread(new Runnable(){
public void run(){
PrepareItem(webrss);
runOnUiThread(new Runnable(){
public void run() {
if(dialog.isShowing()){
try {
setDataToHandels();
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("SET DATA TO HANDELS: " + e);
}
dialog.dismiss();
}
}
});
}
});
thread.start();
break;
private void PrepareItem(String url) {
System.out.println(url);
Document content= null;
try {
content = Jsoup.connect(url).userAgent("Mozilla").timeout(10*1000).get();
} catch (final IOException e) {
// TODO Auto-generated catch block
System.out.println("IOException: " + e.toString());
}
int i=0;
try {
Elements html1 = content.getElementById("main-wrapper").getElementsByTag("div").get(16).children();
html1.select("img").first().remove();
String[] main_content= new String[html1.size()];
i=0;
for (Element element_src : html1.select("div")) {
if (element_src.attr("dir").equals("ltr")) {
main_content[i] = element_src.toString();
i++;
}
}
for (int j = 0; j < main_content.length-2; j++) {
all_text = all_text+main_content[j];
}
all_images_ems = html1.select("img");
all_images_src = new String[all_images_ems.size()];
i=0;
for (Element img_src : all_images_ems) {
all_images_src[i] = img_src.attr("src");
i++;
}
anchor_link_ems = html1.select("a");
all_links = new String[anchor_link_ems.size()];
i=0;
for (Element anchor_links : anchor_link_ems) {
all_links[i] = anchor_links.attr("href");
i++;
}
} catch (NullPointerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Please help me in this regard.
There's a slash at the end of the url.
http://www.apkmania.co/2013/07/blood-sword-thd-v16-apk.html/
If you remove the slash at the end, it should work.
http://www.apkmania.co/2013/07/blood-sword-thd-v16-apk.html
Edit:
It's working for me like this.
String url = "http://www.apkmania.co/2013/07/blood-sword-thd-v16-apk.html";
Document content = null;
try {
content = Jsoup.connect(url).userAgent("Mozilla").timeout(10*1000).get();
} catch (final IOException e) {
// TODO Auto-generated catch block
System.out.println("IOException: " + e.toString());
}
System.out.println(content);
And I'm getting
<!DOCTYPE html PUBLIC "- ...
I solved the problem here is the code if anybody in future needs
String url = "http://www.apkmania.co/2013/07/blood-sword-thd-v16-apk.html"
URL url1;
InputStream in = null;
try {
url1 = new URL(url);
URLConnection urlConnection = url1.openConnection();
in = new BufferedInputStream(urlConnection.getInputStream());
} catch (MalformedURLException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
Document content= null;
try {
content = Jsoup.parse(in, "UTF-8", url);
} catch (IOException e1) {
// TODO Auto-generated catch block
System.out.println(e1.getMessage());
e1.printStackTrace();
}
I am creating a desktop application in which multiple clients have to connect to the server using socket connection between them. I successfully connected them but the problem occurs when i connect multiple client simultaneously to the server, sever got an error "socket write error"
my code is below plz suggest me an answer..
public class SocketConnection implements Runnable {
// password of oracle database
ServerSocket serverSocket = null;
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
Socket clientSocket = null;
DBConnection dbConnection;
public SocketConnection() {
// TODO Auto-generated constructor stub
dbConnection = new DBConnection();
if (con != null) {
serverSocket = dbConnection.createSocket();
if (serverSocket != null) {
System.out.println("Server Started. Looking for the connections.");
System.out.println("Listening Port:8888.......");
}
Thread t = new Thread(this);
t.start();
}
}
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
clientSocket = serverSocket.accept();
System.out.println("Connection Accepted");
Connect m_connect = new Connect(clientSocket);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public class Connect implements Runnable {
Socket clientSocket = null;
Thread t = null;
private ResultSet res1;
private ResultSet res2;
Statement stmt;
private File mkFolder;
public Connect(Socket clientSocke) {
// TODO Auto-generated constructor stub
this.clientSocket = clientSocke;
try {
stmt = con.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
t = new Thread(this);
t.start();
}
#Override
public void run() {
try {
dataInputStream = new DataInputStream(
clientSocket.getInputStream());
dataOutputStream = new DataOutputStream(
clientSocket.getOutputStream());
System.out.println("Connection established::"
+ clientSocket.getInetAddress());
String pass = dataInputStream.readUTF();
System.out.println(pass);
if (pass.equals("1")) {
//here is read n write operation
} else if (pass.equals("3")) {
//here is read n write operation
} else if (pass.equals("2")) {
//here is read n write operation
} else if (pass.equals("4")) {
//here is read n write operation
} else if (pass.equals("5")) {
//here is read n write operation
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Why you are doing this in that low-level way? Choose an well documented API and communicate through it!
Did you already read articles like this: Multithread client server chat on sockets. Load test. recv failed