Investigating the Servlets I've created a simple chat and tested it on local IP - everything works. But when I tried to test it through the real network the connection refused - java.net.ConnectException: Connection refused: connect. Is the reason in Dynamic IP which I have, or additional settings are needed? Thanks in advance!
Server:
/**
* Created by rnd on 7/4/2017.
*/
import java.io.*;
import java.net.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;
public class VerySimpleChatServer {
ArrayList clientOutputStreams;
public static void main (String[] args) {
new VerySimpleChatServer().go();
}
public void go() {
clientOutputStreams = new ArrayList();
try {
ServerSocket serverSock = new ServerSocket(5000);
while(true) {
Socket clientSocket = serverSock.accept();
Charset charset = StandardCharsets.UTF_8;
OutputStreamWriter osw = new OutputStreamWriter( clientSocket.getOutputStream(), charset );
PrintWriter writer = new PrintWriter( new BufferedWriter( osw ) );
// PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
writer.println("Welcome to the chat 7 kids.... Семеро Козлят");
writer.flush();
clientOutputStreams.add(writer);
Thread t = new Thread(new ClientHandler(clientSocket));
t.start() ;
System.out.println("got a connection");
}
} catch(Exception ex) {
ex.printStackTrace();
}
} // Закрываем go
public class ClientHandler implements Runnable {
BufferedReader reader;
Socket sock;
public ClientHandler(Socket clientSocket) {
try {
sock = clientSocket;
InputStreamReader isReader = new InputStreamReader(sock.getInputStream(), StandardCharsets.UTF_8);
reader = new BufferedReader(isReader);
} catch(Exception ex) {ex.printStackTrace();}
} // Закрываем конструктор
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
System.out.println("read " + message);
tellEveryone(message);
} // Закрываем while
} catch(Exception ex) {ex.printStackTrace();}
} // Закрываем run
} // Закрываем вложенный класс
public void tellEveryone(String message) {
Iterator it = clientOutputStreams.iterator();
while(it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
writer.flush();
} catch(Exception ex) {
ex.printStackTrace();
}
} // Конец цикла while
} // Закрываем tellEveryone
} // Закрываем класс
Client:
/**
* Created by rnd on 7/4/2017.
*/
import java.io.*;
import java.net.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class SimpleChatClient {
JTextArea incoming;
JTextField outgoing;
BufferedReader reader;
PrintWriter writer;
Socket sock;
public static void main(String[] args) {
SimpleChatClient client = new SimpleChatClient();
client.go();}
public void go(){
JFrame frame = new JFrame("Ludicrously Simple Chat Client");
JPanel mainPanel = new JPanel();
incoming = new JTextArea(15,50);
incoming.setLineWrap(true);
incoming. setWrapStyleWord (true) ;
incoming.setEditable(false);
JScrollPane qScroller = new JScrollPane(incoming);
qScroller. setVerticalScrollBarPolicy (ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS) ;
qScroller. setHorizontalScrollBarPolicy (ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS) ;
outgoing = new JTextField(20);
JButton sendButton = new JButton("Send") ;
sendButton.addActionListener(new SendButtonListener());
mainPanel.add(qScroller);
mainPanel.add(outgoing);
mainPanel.add(sendButton);
setUpNetworking();
Thread readerThread = new Thread(new IncomingReader());
readerThread.start();
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.setSize(800,500);
frame.setVisible(true);
}
private void setUpNetworking() {
try {
sock = new Socket("178.165.87.221", 5000);
InputStreamReader streamReader = new InputStreamReader(sock.getInputStream(), StandardCharsets.UTF_8 );
reader = new BufferedReader(streamReader);
Charset charset = StandardCharsets.UTF_8;
OutputStreamWriter osw = new OutputStreamWriter( sock.getOutputStream(), charset );
writer = new PrintWriter( new BufferedWriter( osw ) );
// writer = new PrintWriter(sock.getOutputStream());
System.out.println("networking established");
} catch (IOException ex) {
ex.printStackTrace();}
}
public class SendButtonListener implements ActionListener {
public void actionPerformed (ActionEvent ev) {
try {
writer.println(outgoing.getText());
writer.flush();
} catch(Exception ex) {
ex.printStackTrace();
}
outgoing. setText ("") ;
outgoing.requestFocus () ;}
}
public class IncomingReader implements Runnable{
#Override
public void run() {
String message;
try{
while((message=reader.readLine())!=null ){
System.out.println("read " + message);
incoming.append(message + "\n");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
If you really have a dynamic ip, you can get yourself a freedns domain (and add a firewall exception), but most probably you're behind NAT. To make it work you need multiple things:
Still, get a freedns domain and setup automatic ip address update
hardcode the domain in the client
expose a fixed set of UDP ports by sending UDP packets to nowhere. The UDP port number on public ip usually matches the port number on your host. This part is the most important. You can check it works using public STUN/TURN servers.
Hardcode this set of ports into the client. It should try all ports on the freedns domain, until it finds a working port
The handshake packets should have a signature unique for your chat so both sides know they're trying to connect to the right software
As it appears, most NATs are Port-restricted cone NATs, that is, they drop incoming UDP packets from a peer until you send a packet to that peer. Besides, NAT UDP mappings you create by sending a packet expire in around 60 seconds, which is much less than for TCP mappings.
All this makes pure p2p messaging impossible for parties behind NAT. To join a p2p network you still need to exchange a few packets via a public server (e-mail or another Instant messaging provider). There's the library "ice4j" that can produce and parse these packets (SDP) and then create java socket wrappers for direct connections.
And even if two peers save each other's addresses to connect directly in the future, the addresses will eventually expire due to dynamic ip (usually 24h).
Sounds like either a firewall refusing the connection or a router is not port forwarding, so the request is just being refused. It doesn't sound like anything to do with having a dynamic IP.
If you are behind a router then there are settings in the router to allow port forwarding, and you might need to add a rule to your firewall. Anyway you can test by just trying to ping the server IP address from elsewhere and if that responds then even try a telnet <server ip> port to see if you can connect.
Something is getting in the way and refusing the connection!
Related
I wanted to send a string of text from my android phone over to a Java server running on my PC and it works but only once, it would receive the first string but when I type in another one on my phone and I press the button, the server doesn't receive anything, (here is my code for the android app):
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
messsage = etMsg.getText().toString();
etMsg.setText("");
new Thread(new Runnable() {
#Override
public void run() {
try
{
client = new Socket(etIP.getText().toString(), port);
printwriter = new PrintWriter(client.getOutputStream());
printwriter.write(messsage);
printwriter.flush();
printwriter.close();
client.close();
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}).start();
}
});
And here is the code for the Java server:
package src;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class VRS {
public static void main(String[] args) throws IOException {
Socket clientSocket = null;
ServerSocket serverSocket = null;
try{
serverSocket = new ServerSocket(4444);
System.out.println("server started on port 4444");
clientSocket = serverSocket.accept();
}catch(Exception e){} //read & display the message
//BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
Scanner in1 = new Scanner(clientSocket.getInputStream());
String mes;
while(true){
if (in1.hasNext())
{
mes=in1.nextLine();
System.out.println("Client message :"+mes + System.lineSeparator());
}
}
}
}
Can anyone help me find the problem as I'm a beginner in terms of Java.
The scanner on the server is waiting for a complete token with a terminator and you are not sending one from the client. Try appending a line terminating character on the client side e.g.
printwriter.println(messsage);
In addition to that it seems that for every click on the client side a new Socket object is created. But the server is not waiting for a new connection. You can either :
reuse the Socket on the client side instead of creating a new one for every click. e.g. make your client variable a class member.
On the server side after each message call clientSocket = serverSocket.accept(); again to create a new Socket. This new server side Socket will correspond to the new Socket on the client.
The first option is considered more efficient especially as the number of connections and messages you want to handle increases.
I'm making a simple java server & client for Educational purposes while finishing learning the Connections chapters in java language, and I had several problems while running the program, so i would be glad if I could get any kind of help to solve my problem, I had a main problems while running it
Problem : A text doesn't get sent both sides, I have made 2 clients, when I send text from client 1 for exemple to client 2, its all good, but vise-versa it doesn't
Sourse Code: main class
public class Start {
public static void main(String [] args) {
chatserver server = new chatserver();
server.go();
chatclient chat = new chatclient();
chat.go();
chatclient2 chat2 = new chatclient2();
chat2.go();
}
}
First Client class:
import java.io.*;
import java.net.*;
import java.util.*;
import javax.swing.*;
import java .awt.*;
import java.awt.event.*;
public class chatclient {
JTextArea incoming;
JTextField outgoing;
BufferedReader reader;
PrintWriter writer;
Socket sock;
public void go() {
JFrame frame = new JFrame("Simple Chat Client V.1");
JPanel mainPanel = new JPanel() ;
incoming = new JTextArea(15,50);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true) ;
incoming.setEditable(false);
JScrollPane qScroller = new JScrollPane(incoming) ;
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
outgoing = new JTextField(30);
JButton sendButton = new JButton("Send");
sendButton.addActionListener(new sendz());
mainPanel.add (qScroller) ;
mainPanel.add(outgoing);
mainPanel.add(sendButton);
connectinsetup();
Thread thread = new Thread(new reader());
thread.start();
frame.getContentPane().add(BorderLayout.CENTER,mainPanel);
frame.setSize(500,500);
frame.setVisible(true);
}
public void connectinsetup() {
try{
Socket socket = new Socket("127.0.0.1",5000);
InputStreamReader stream = new InputStreamReader(socket.getInputStream());
reader = new BufferedReader(stream);
writer = new PrintWriter(socket.getOutputStream());
System.out.println("Connection Established");
}
catch(IOException ex) {
ex.printStackTrace();
}
}
public class sendz implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
try{
writer.println(outgoing.getText());
writer.flush();
}
catch(Exception exz){
exz.printStackTrace();
}
outgoing.setText("");
outgoing.requestFocus();
}
}
public class reader implements Runnable{
public void run() {
String msg;
try{
while ( (msg = reader.readLine() ) != null) {
incoming.append(msg + "\n");
}
}
catch(Exception ex){
ex.printStackTrace();
}
}
}
}
Server Class:
import java.io.*;
import java.net.*;
public class chatserver {
PrintWriter writer;
public void go() {
try{
ServerSocket socket = new ServerSocket(5000);
while(true) {
Socket serversocket = socket.accept();
Thread thread = new Thread(new clienthandler(serversocket));
thread.start();
writer = new PrintWriter(serversocket.getOutputStream());
}
}
catch (Exception ex) {
ex.printStackTrace();
}
} // end go method
public class clienthandler implements Runnable {
Socket sock;
BufferedReader reader;
public clienthandler( Socket socks) {
try{
sock = socks;
InputStreamReader stream = new InputStreamReader(socks.getInputStream());
reader = new BufferedReader(stream);
}
catch(IOException ex) {
ex.printStackTrace();
}
}
public void run() {
String msg;
try{
while((msg = reader.readLine())!= null ) {
tellall(msg);
}
}
catch(Exception ex) {
ex.printStackTrace();
}
}
} //end clienthandler class
public void tellall(String text){
String msgall = text;
try{
writer.println(msgall);
writer.flush();
}
catch(Exception ex){
ex.printStackTrace();
}
} //end tellall method
}//end chatserver
And this is the Exceptions i get guys:
java.net.BindException: Address already in use: JVM_Bind
at java.net.DualStackPlainSocketImpl.bind0(Native Method)
at java.net.DualStackPlainSocketImpl.socketBind(Unknown Source)
at java.net.AbstractPlainSocketImpl.bind(Unknown Source)
at java.net.PlainSocketImpl.bind(Unknown Source)
at java.net.ServerSocket.bind(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at java.net.ServerSocket.<init>(Unknown Source)
at test.chatserver.go(chatserver.java:12)
at test.Start.main(Start.java:12)
I hope to be helpful, I would say it has some bugs in your code such as:
chatclient chat = new chatclient();
chat.go();
chatclient2 chat2 = new chatclient2();
chat2.go();
You dont have any chatclient2, you should do:
chatclient chat = new chatclient();
chat.go();
chatclient chat2 = new chatclient();
chat2.go();
Otherwise, if you dont put the server in a different thread, the application will be frozen as it will be waiting for clients to connect (and the beginning of customers is below) is solved as easy as:
new Thread() {
public void run() {
chatserver server = new chatserver();
server.go();
}
}.start();
and in response to your question of why only text appears in one of the clients is because when you do on the server:
Socket serversocket = socket.accept();
Thread thread = new Thread(new clienthandler(serversocket));
thread.start();
writer = new PrintWriter(serversocket.getOutputStream());
each time a client connects, the 'writer' is overwritten with the last client socket (Each client has its own socket and with which we can communicate with he)
You can fix it doing for example an array of different writer with sockets ..
Greetings, I hope to be helpful = D
The BindException is thrown because the port is already in use.
There could be 2 reasons for that:
A Socket continues to run even when your program has already been terminated if you do not manually call .close().
The port is used by another service (for example web-server, database-server, ...)
I suspect option 1 is reason for your particular Exception. Just try another port or manually kill the java-background-task and then try running your program again (and close the sockets this time properly).
When to close the Sockets:
At first i would add a method shutdown() to both the client and the server. In these methods you just close all socket-instances you have, like for example here (you may need some catch-blocks though):
public void shutdown() {
serverSocket.close();
/* close other sockets here */
}
Then you add a WindowListener to both of the client-GUIs and do in windowClosing():
public void windowClosing(WindowEvent evt) {
client.shutdown();
}
For closing the server you could add the following code to the main-method:
System.out.println("Press Enter to stop the server ...");
System.in.read(); // wait for an "Enter"-press in the console
server.shutdown();
When closing a connected Socket, some Exceptions will probably be thrown on the other end of the connection. So don't forget to put appropriate catch-blocks there.
I'm new to the network communication and I'm trying to build client-server application.
protected void init(){
Server myServer = new Server();
Client myClient = new Client();
}
That's my Client class:
public class Client {
public Client() {
init();
}
private void init() {
Socket echoSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
DataInputStream stdIn = new DataInputStream(System.in);
try {
echoSocket = new Socket("localhost", 1234);
os = new DataOutputStream(echoSocket.getOutputStream());
is = new DataInputStream(echoSocket.getInputStream());
os.writeInt(stdIn.readInt());
echoSocket.getOutputStream().close();
echoSocket.getInputStream().close();
echoSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And that's server:
public class Server {
public Server() {
init();
}
private void init() {
try {
boolean run = true;
ServerSocket ss = new ServerSocket(1234);
Socket s = ss.accept();
DataInputStream dis = new DataInputStream(s.getInputStream());
System.out.println(dis.readInt());
s.getInputStream().close();
s.getOutputStream().close();
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
First of all:
Can I initialize client and server simply like i did? new Server() and new Client()?
Question 2:
Is it important what i initialize at first? client or server?
Question 3:
When i compile this code with client first initialized, i become Connection refused: connect. I know it means that there is no listening socket running on the port you are trying to connect to. That's why server must go first, i think. Is it so? can i fix it using setSoTimeout and how?
Question 4:
When i compile it with server and then client, output is nothing. And i think it has nothing to do with client, because if i try to print "1", for example, it doesn't work either. I think it just waits for the client and does nothing that goes after. How can i fix this? maybe setSoTimeout goes here too?
You can't have both client and server in the same thread.
As you already have observed, the server accepts the connection and tries to read something. It doesn't know that the client is running in the very same thread.
Either make a multi-threaded application, where client and server have their own thread. Or make two prgrams that run independently of each other. The latter would be also the "normal case".
Make two different projects, first run server than client.
Server will write on console "Server started" than run client it will ask your name, type your name press ok . Your name will be sent to server and server will reply saying hello to you.
Here is server code
import java.net.*;
import java.io.*;
import javax.swing.*;
public class Server {
public static void main(String[] args) {
try{
ServerSocket ss= new ServerSocket(2224);
System.out.println("Serever started");
while(true)
{
Socket s=ss.accept();
InputStream is=s.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
OutputStream os=s.getOutputStream();
PrintWriter pw=new PrintWriter(os);
String name=br.readLine();
String message="Hello "+name+"from server";
pw.println(message);
pw.flush();
}
}
catch(Exception exp)
{
System.out.println("Excepttion occured");
}
}
}
Here is client code
import java.net.*;
import java.io.*;
import java.util.Scanner;
import javax.swing.*;
public class Client {
public static void main(String[] args) throws IOException {
Socket s=new Socket("localhost",2224);
InputStream is=s.getInputStream();
InputStreamReader isr=new InputStreamReader(is);
BufferedReader br=new BufferedReader(isr);
OutputStream os=s.getOutputStream();
PrintWriter pw=new PrintWriter(os,true);
String message = JOptionPane.showInputDialog("Give your name");
pw.println(message);
pw.flush();
String servermessage = br.readLine();
JOptionPane.showMessageDialog(null, servermessage);
s.close();
}
}
I'm trying to interconnect two socket clients connected to a single remote server.
The case is:
Client_1] connect to the server
Client_2] connect to the server
Server] create a tunnel between Client_1 and Client_2
Client_1] write "something"
Client_2] (that is waiting for some messages) receive "something" by Client_1
and viceversa.
That's my code:
package jtestsock;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
/**
*
* #author massimodeluisa
*/
public class Server extends Thread{
private List<Socket> clients;
private ServerSocket server;
private int port = 5001;
private BufferedReader input;
private PrintWriter output;
public Server() {
try {
server = new ServerSocket(port);
} catch (IOException e) {
System.out.println("Impossibile istanziare il server: "+e.getMessage());
}
}
#Override
public void run() {
System.out.println("Waiting for client message...");
//
// The server do a loop here to accept all connection initiated by the
// client application.
//
while (true) {
try {
Socket socket = server.accept();
System.out.println("Connection Received!");
clients.add(socket);
/* read response */
input = new BufferedReader(
new InputStreamReader(
socket.getInputStream()));
output = new PrintWriter(
new BufferedWriter(
new OutputStreamWriter(
socket.getOutputStream())));
if(clients.size()>0){
Socket first = new Socket();
Socket second = new Socket();
first = clients.get(1);
second= clients.get(2); // || second = socket;
// ??? Tunneling input and output between two clients
}
} catch (IOException e) {
System.out.println("Client connection error: "+e.getMessage());
}
}
}
}
Can anyone help me please?
Thanks :)
Update:
I would like to make a Point to Point connection between two clients, passing to my server, like a proxy server...
The server must accept more than two connection, and making two threads on the server for writing and reading that redirect messages from one client to the other, the CPU will be saturated.
(Ps. sorry for my English XD)
I would do it this way (simplified version):
class Server extends Thread
...
public void run() {
while (true) {
try {
Socket s1 = server.accept();
Socket s2 = server.accept();
new Client(s1, s2).start(); // reads from s1 and redirects to s2
new Client(s2, s1).start(); // reads from s2 and redirects to s1
} catch (IOException e) {
System.out.println("Client connection error: " + e.getMessage());
}
}
}
class Client extends Thread {
Socket s1;
Socket s2;
Client(Socket s1, Socket s2) {
this.s1 = s1;
this.s2 = s2;
}
public void run() {
try {
InputStream is = s1.getInputStream();
OutputStream os = s2.getOutputStream();
for (int i; (i = is.read()) != -1; i++) {
os.write(i);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have a java program that will connect the client to the server.
This includes making a file directory once the client had triggered the server through sending a message. For example: Once the server is running already, the client will then connect and will send a msg i.e "Your message: Lady", the server will receive a message like "Request to create a Directory named: Lady", after this a directory will be created named Lady.
But the problem is this connection is only for one-to-one. Like only one client can connect to the server...
This is the sample code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package today._;
import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;
public class myServer {
protected static final int PORT_NUMBER = 55555;
public static void main(String args[]) {
try {
ServerSocket servsock = new ServerSocket(PORT_NUMBER);
System.out.println("Server running...");
while (true) {
Socket sock = servsock.accept();
System.out.println("Connection from: " + sock.getInetAddress());
Scanner in = new Scanner(sock.getInputStream());
PrintWriter out = new PrintWriter(sock.getOutputStream());
String request = "";
while (in.hasNext()) {
request = in.next();
System.out.println("Request to Create Directory named: " + request);
if(request.toUpperCase().equals("TIME")) {
try {
File file = new File("C:\\" + request);
if (!file.exists()) {
if (file.mkdir()) {
System.out.println("Directory is created!");
} else {
System.out.println("Failed to create directory!");
}
}
} catch (Exception e) {
System.out.println(e);
}
out.println(getTime());
out.flush();
} else {
out.println("Invalid Request...");
out.flush();
}
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
}
protected static String getTime() {
DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
Date date = new Date();
return (dateFormat.format(date));
}
}
package today._;
import java.io.*;
import java.net.*;
import java.util.*;
public class myClient {
protected static final String HOST = "localhost";
protected static final int PORT = 55555;
protected static Socket sock;
public static void main(String args[]) {
try {
sock = new Socket(HOST,PORT);
System.out.println("Connected to " + HOST + " on port " + PORT);
Scanner response = new Scanner(sock.getInputStream());
PrintWriter request = new PrintWriter(sock.getOutputStream());
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String txt = "";
while(!txt.toUpperCase().equals("EXIT")) {
System.out.print("Your message:");
txt = in.readLine();
request.println(txt);
request.flush();
System.out.println(response.next());
}
request.close();
response.close();
in.close();
sock.close();
} catch(IOException e) {
System.out.println(e.toString());
}
}
}
Multi-client servers are generally written one of two ways:
Create a thread for each client. To do this you would create a thread to handle the calls to accept() on the server socket and then spawn a new thread to handle calls on the Socket that it returns. If you do this, you need to make sure you isolate the code for each socket as much as possible. The accept thread will loop forever, or until a flag is set, and will just call accept, spawn a thread with the new socket, and go back to calling accept. All of the work is in the child thread.
Use NIO, or another technology, to multi-plex work into 1 more more threads. NIO uses a concept sometimes called select, where your code will be called when there is input available from a specific socket.
If you are just doing a small server, you can go with the simplest design and also won't have too many clients, so I would go with #1. If you are doing a big production server, I would look into a framework like netty or jetty that will help you do #2. NIO can be tricky.
In either case, be very careful with threads and the file system, you might not get the results you expect if you don't use a Lock from the concurrency package, or synchronize, or another locking scheme.
My final advice, be careful with having a client tell a server to do anything with the file system. Just saying, that is a dangerous thing to do ;-)
Your server class must use multiple threads to handle all connections:
class MyServer {
private ServerSocket servsock;
MyServer(){
servsock = new ServerSocket(PORT_NUMBER);
}
public void waitForConnection(){
while(true){
Socket socket = servsock.accept();
doService(socket);
}
}
private void doService(Socket socket){
Thread t = new Thread(new Runnable(){
public void run(){
while(!socket.isClosed()){
Scanner in = new Scanner(sock.getInputStream());
PrintWriter out = new PrintWriter(sock.getOutputStream());
String request = "";
// and write your code
}
}
});
t.start();
}
}