I am creating an application to Send a File from a Client and Receive it with a Server via Socket.
When I test the Application in my PC (Client-Server on same PC) everything runs Ok, but When I test the application on different PCs I've got the following errors.
First Attempt: Nothing happen, no errors, no file sent.
Second Attempt: Java throws an error of Ip already in use, but I receive the file on my Server PC but it has no data on it.
Here is the code for Client:
public class FileSender {
public static void main(String[] args) {
// TODO Auto-generated method stub
FileSender nioClient = new FileSender();
SocketChannel socketChannel = nioClient.createChannel();
try {
nioClient.sendFile(socketChannel);
} catch (FileNotFoundException | InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//SocketChannel socketChannel = nioClient.createc
}
public SocketChannel createChannel(){
SocketChannel socketChannel = null;
try {
socketChannel = SocketChannel.open();
SocketAddress socketAddress = new InetSocketAddress("xx.xxx.xxx.x", 10002);
socketChannel.connect(socketAddress);
System.out.println("Connected..Now Sending the File");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return socketChannel;
}
public void sendFile(SocketChannel socketChannel) throws FileNotFoundException, InterruptedException{
RandomAccessFile afile = null;
try {
File file = new File("/home/dionisio/Imágenes/ImagenesOriginalesPrueba/flowers.jpg");
afile = new RandomAccessFile(file, "r");
FileChannel inChannel = afile.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(8192);
while (inChannel.read(buffer) != -1) {
buffer.flip();
socketChannel.write(buffer);
buffer.clear();
}
socketChannel.close();
afile.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Server Code
public class FileReceiver {
public static void main(String[] args) {
// TODO Auto-generated method stub
FileReceiver nioServer = new FileReceiver();
SocketChannel socketChannel = nioServer.createServerSocketChannel();
nioServer.readFileFromSocket(socketChannel);
}
private SocketChannel createServerSocketChannel() {
// TODO Auto-generated method stub
ServerSocketChannel serverSocketChannel = null;
SocketChannel socketChannel = null;
try {
serverSocketChannel = ServerSocketChannel.open();
serverSocketChannel.socket().bind(new InetSocketAddress(10002));
socketChannel = serverSocketChannel.accept();
System.out.println("Connection Stablished..."+socketChannel.getRemoteAddress());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return socketChannel;
}
private void readFileFromSocket(SocketChannel socketChannel) {
// TODO Auto-generated method stub
RandomAccessFile afile = null;
try {
afile = new RandomAccessFile("/home/dionisio/Imágenes/imagenesCopiaPrueba/flowersCopia.jpg","rw");
ByteBuffer buffer = ByteBuffer.allocate(8192);
FileChannel fileChannel = afile.getChannel();
while (socketChannel.read(buffer)>0) {
buffer.flip();
fileChannel.write(buffer);
buffer.clear();
}
Thread.sleep(1000);
fileChannel.close();
System.out.println("End of file reached...Closing Channel");
socketChannel.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Your read loops aren't correct. They should be of the form:
while (in.read(buffer) > 0 || buffer.position() > 0)
{
buffer.flip();
out.write(buffer);
buffer.compact();
}
Otherwise you can lose data.
NB
Java does not throw an error 'IP already in use'. Be accurate.
You don't need the sleep. Don't add sleeps to networking code. It doesn't solve anything.
My folks thanks for your replies, now I know what was my error, I was putting the wrong Ip address on my client Application.
However EJP I will take your recommendation for a better byte check when writing on a Channel.
Related
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.
I have a Java Server and one(or more) Android Clients. For now I want them to communicate simply with strings. When i write from android I can get the data in Java Server, but when I try to get the answer from server the Android application stop working. The codes is reported below:
Java Server:
public class Server {
private static int port=12346, maxConnections=0;
// Listen for incoming connections and handle them
public static void main(String[] args) {
int i=0;
try{
ServerSocket listener = new ServerSocket(port);
Socket server;
while((i++ < maxConnections) || (maxConnections == 0)){
doComms connection;
server = listener.accept();
String end = server.getInetAddress().toString();
System.out.println("\n"+end+"\n");
doComms conn_c= new doComms(server);
Thread t = new Thread(conn_c);
t.start();
}
} catch (IOException ioe) {
System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
}
class doComms implements Runnable {
private Socket server;
private String line,input;
public doComms(Socket server) {
this.server=server;
}
#SuppressWarnings("deprecation")
public void run () {
input="";
try {
// Get input from the client
DataInputStream in = new DataInputStream (server.getInputStream());
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(server.getOutputStream())),
true);
while((line = in.readLine()) != null && !line.equals(".")) {
input=input + line;
}
JOptionPane.showMessageDialog(null, input);
out.println("Enviado");
server.close();
} catch (IOException ioe) {
System.out.println("IOException on socket listen: " + ioe);
ioe.printStackTrace();
}
}
And Android client's code (it's called every time a button is pressed inside onClick method):
public String enviaMensagem(){
String resposta="";
new Thread(new ClientThread()).start();
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket(ip, port);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(input.getText().toString());
resposta = dataInputStream.readUTF();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} 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();
}
}
}
return resposta;
}
You are using an unsorted mixture of readUTF(), writeUTF(), readLine(), etc. They're not all interoperable. Settle on one of them. If you use writeUTF() you must use readUTF() at the other end. If you use readLine() you must write lines at the other end, with a line terminator such as \r\n or \n.
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I'm writing simple client - server application but I have stupid problem with this (it simplify example (everything is ok when i don't use java serialization)):
ServerSocket serversocket=null;
Socket socket=null;
String slowo=null;
try {
serversocket=new ServerSocket(8877);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket=serversocket.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
slowo=(String)ois.readObject();
My compiler shows:
Serwer.java:51: cannot find symbol
symbol : variable ois
location: class Serwer
slowo=(String)ois.readObject();
^
1 error
Can anyone help?
I have one more question. Why this program don't send messages ?
Serwer.java :
public class Serwer {
public static void main(String[] args) {
ServerSocket serversocket=null;
Socket socket=null;
InputStream we=null;
OutputStream wy=null;
BufferedReader odczyt=null;
BufferedReader odczytWe=null;
DataOutputStream zapis=null;
String slowo=null;
String tekst=null;
ObjectInputStream ois=null;
ObjectOutputStream oos=null;
try {
serversocket=new ServerSocket(8877);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket=serversocket.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ois = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
oos=new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//slowo=(String)ois.readObject();
while(true) {
try {
slowo=(String) ois.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(slowo==null || slowo.equals("end")) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.exit(0);
}
else if(slowo!=null) {
System.out.println(slowo);
}
odczyt=new BufferedReader(new InputStreamReader(System.in));
try {
tekst=odczyt.readLine();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
oos.writeObject(tekst);
oos.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
Klient.java :
public class Klient {
public static void main(String[] args) {
Socket socket=null;
InputStream we=null;
OutputStream wy=null;
BufferedReader odczyt=null;
BufferedReader odczytWe=null;
DataOutputStream zapis=null;
String slowo=null;
String tekst=null;
ObjectInputStream ois=null;
ObjectOutputStream oos=null;
try {
socket=new Socket("localhost", 8877);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ois=new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
oos=new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while(true) {
try {
slowo=(String) ois.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(slowo==null || slowo.equals("end")) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.exit(0);
}
else if(slowo!=null) {
System.out.println(slowo);
}
odczyt=new BufferedReader(new InputStreamReader(System.in));
try {
tekst=odczyt.readLine();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
oos.writeObject(tekst);
oos.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
It's out of scope by the time you get to line 51 because you declare it in the previous try.
Move the declaration outside of both, or write the code differently.
I consider this style to be cluttered and hard to read. I'd write it like this:
ServerSocket serversocket=null;
String slowo="";
try {
serversocket=new ServerSocket(8877);
Socket socket = serversocket.accept();
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
ObjectOutputStream oos=new ObjectOutputStream(socket.getOutputStream());
slowo=(String)ois.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
close(serversocket);
}
Don't let a bad IDE write bad code for you.
You should close your socket in a finally block.
I'm writing simple client - server application. Everything is ok but when i change InputStream and OutputStream to ObjectOutputStream and ObjectInputStream my application doesn't send the messages. Can anyone help me and show me the problem ?
Here is the Serwer.java:
class InWorke implements Runnable{
BufferedReader odczyt=null;
String slowo;
ObjectInputStream ois=null;
Message message;
InWorke(ObjectInputStream ois) {
this.ois=ois;
}
public void run() {
while(true) {
try {
slowo = (String) ois.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(slowo);
Thread.yield();
} }
}
class OutWorke implements Runnable{
Socket socket=null;
BufferedReader odczytWe=null;
DataOutputStream zapis=null;
String slowo=null;
Message message; // it is the simple class to serialization
ObjectOutputStream oos;
OutWorke(Socket socket,ObjectOutputStream oos) {
this.socket=socket;
this.oos=oos;
}
public void run() {
while(true) {
odczytWe=new BufferedReader(new InputStreamReader(System.in));
try {
slowo=odczytWe.readLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
oos.writeObject(slowo);
oos.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Thread.yield();
}
}
}
public class Klient {
public static void main(String[] args) {
Socket socket=null;
ExecutorService exec=Executors.newCachedThreadPool();
ObjectOutputStream oos=null;
ObjectInputStream ois=null;
try {
socket=new Socket("localhost", 8881);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
//we=socket.getInputStream();
ois=new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
//wy=socket.getOutputStream();
oos=new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
exec.execute(new OutWorke(socket, oos));
exec.execute(new InWorke(ois));
}
}
Klient.java:
class InWorker implements Runnable{
Socket socket=null;
//InputStream we=null;
//OutputStream wy=null;
String slowo=null;
BufferedReader odczyt=null;
ObjectOutputStream oos;
ObjectInputStream ois;
Message message=null;
InWorker(Socket socket,ObjectInputStream ois) {
this.socket=socket;
this.ois=ois;
}
public void run() {
while(true) {
try {
slowo=(String) ois.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(slowo);
Thread.yield();
}
}
}
class OutWorker implements Runnable{
DataOutputStream zapis=null;
BufferedReader odczyt=null;
//OutputStream wy=null;
String tekst=null;
ObjectOutputStream oos=null;
Message message;
OutWorker(ObjectOutputStream oos) {
this.oos=oos;
}
public void run() {
while(true) {
odczyt=new BufferedReader(new InputStreamReader(System.in));
try {
tekst=odczyt.readLine();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
oos.writeObject(tekst);
oos.flush();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Thread.yield();
}
}
}
public class Serwer {
public static void main(String[] args) {
ServerSocket serversocket=null;
Socket socket=null;
//InputStream we=null;
//OutputStream wy=null;
ObjectOutputStream oos=null;
ObjectInputStream ois=null;
ExecutorService exec=Executors.newCachedThreadPool();
try {
serversocket=new ServerSocket(8881);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
socket=serversocket.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ois=new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
oos=new ObjectOutputStream(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
exec.execute(new InWorker(socket, ois));
exec.execute(new OutWorker(oos));
}
}
Check constructor of ObjectInputStream: constructor.
It says:
This constructor will block until the corresponding ObjectOutputStream
has written and flushed the header.
So you need to create and flush corresponding ObjectOutputStream. Now you are creating ObjectInputStreams before output stream for both server and client. They block programs because no output stream is created. You should create output streams first, call flush on them and only then create input streams.
The root issue is just as Nikita points out. The implementation solution is to have the server and client get the input and output streams in the opposite order. If one is getting the inputstream first have the other get the outputstream, etc. I switched the client to get the outputstream first and it all works. I then put it back and change the Server and it all works that way to... you can choose which to change.
For Reference:
http://docs.oracle.com/javase/6/docs/api/index.html?java/io/ObjectOutputStream.html
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