I'm trying to learn how to use java sockets before next semester. I wrote this program that is supposed to accept accept a message from a sender and send the message to a reciever. You specify the reciever by writing the name of the client that is connected, if the client isn't connected then the server will respond by sending the message "DISCONNECTED". But for some reason the message isn't sent to the reciever. I can still send the message to the sender though. Is this the right forum to ask for this kind of help?
This is my client class
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class MyTestClient {
static int port = 0;
static String ip = "";
static String name = "";
public static void main(String args[] ) {
if(args.length == 3) {
try{
port = Integer.parseInt(args[1]);
} catch(NumberFormatException e) {
System.out.println("Usage: Java MyTestClient <ip> <port> <name>");
System.exit(0);
}
ip = args[0];
name = args[2];
} else {
System.out.println("Usage: Java MyTestClient <ip> <port> <name>");
System.exit(0);
}
try {
Socket socket = new Socket(ip, port);
new Thread(new MessageHandler(socket)).start();
new Thread(new InputHandler(socket)).start();
} catch (IOException e) {
System.out.println("Could not connect to: " + ip + " : " + port);
System.exit(0);
}
}
public static class MessageHandler implements Runnable {
Socket socket;
public MessageHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
PrintWriter out = null;
BufferedReader in = null;
try {
out = new PrintWriter(socket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}catch(IOException e) {
e.printStackTrace();
}
String fromServer;
try {
while ((fromServer = in.readLine()) != null) {
System.out.println(fromServer);
fromServer.trim();
if(fromServer.contains(" ")) {
String split[] = fromServer.split(" ", 2);
System.out.println(split.length == 2 ? split[1] + " Is a two part message" : "Strange message");
} else {
if(fromServer.equals("NAME")) {
System.out.println("Server asks for name | gives given name to server");
out.println(name);
}
if(fromServer.equals("SUCCESS")) {
System.out.println("Message succesfully sent");
}
if(fromServer.equals("ERROR")) {
System.out.println("Something went wrong when sending the message");
}
if(fromServer.equals("OCCUPIED")) {
System.out.println("Name was already used. Start the program with another name");
socket.close();
System.exit(0);
}
if(fromServer.equals("DISCONNECTED")) {
System.out.println("The reciever was not connected");
}
if(fromServer.equals("REGISTERED")) {
System.out.println("Successfully logged in to server");
}
}
}
} catch(IOException e) {
e.printStackTrace();
}
}
}
public static class InputHandler implements Runnable {
Socket socket;
public InputHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
String fromUser = null;
PrintWriter out = null;
try {
out = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader kbi = new BufferedReader(new InputStreamReader(System.in));
try {
while ((fromUser = kbi.readLine()) != null) {
out.println(fromUser);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
This is my server class
import java.io.*;
import java.net.*;
import java.util.*;
public class MyServer {
public static int port;
public static int maxConnections;
public static final String NAME = "Server";
private static Map<String, Socket> socketsMap = new HashMap<>();
public static void main(String args[]) {
if(args.length == 2) {
try{
port = Integer.parseInt(args[0]);
maxConnections = Integer.parseInt(args[1]);
}catch(Exception e){
System.out.println("Usage: Java Myserver <port> <maxConnections>");
System.exit(0);
}
} else {
System.out.println("Usage: Java Myserver <port> <maxConnections>");
System.exit(0);
}
new Thread(new ConnectionHandler(port, maxConnections)).start();
}
public static class ConnectionHandler implements Runnable {
private ServerSocket server;
private Socket socket = null;
public int currentSocket = 0;
public int port = 0;
public int maxConnections = 0;
public ConnectionHandler(int port, int maxConnections) {
this.maxConnections = maxConnections;
this.port = port;
}
#Override
public void run() {
try {
server = new ServerSocket(7777);
} catch (IOException e1) {
System.out.println("Server could not connect to port: " + port);
e1.printStackTrace();
System.exit(0);
}
while(currentSocket++ < maxConnections) {
try {
socket = server.accept();
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println("NAME");
String message;
while((message = in.readLine()) != null) {
if(!socketsMap.containsKey(message) || message.equals("SERVER")) {
out.println("REGISTERED");
socketsMap.put(message, socket);
System.out.println(message + " has logged on server");
new Thread(new SocketHandler(socketsMap.get(message))).start();
} else {
out.println("OCCUPIED");
System.out.println(socket.getInetAddress().toString() + " has tried to login with existing name " + message);
socket.close();
currentSocket--;
}
socket = null;
break;
}
} catch (IOException e) {
System.out.println("Something went wrong with client connection");
}
}
}
}
public static class SocketHandler implements Runnable {
Socket socket = null;
public SocketHandler(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter respond = new PrintWriter(socket.getOutputStream(), true);
String input;
while((input = in.readLine() ) != null) {
String[] info = input.split(" ", 2);
if(info.length != 2){
System.out.println("Message computed wrong");
respond.println("ERROR");
break;
}
if(info[0].equals("SERVER")) {
//TODO: Write a server command handler class
} else if ( socketsMap.containsKey(info[0]) ){
Socket reciever = socketsMap.get(info[0]);
PrintWriter out = new PrintWriter(reciever.getOutputStream());
respond.println("SUCCESS");
System.out.println(info[0] + " send the message: "+ info[1]);
out.println("MESSAGE" + " " + info[1]);
break;
} else {
System.out.println("Reciever is not connected");
respond.println("DISCONNECTED");
}
}
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
Maybe you can run it on your computers and see what i mean?
#Override
public void run() {
try {
server = new ServerSocket(7777);
} catch (IOException e1) {
System.out.println("Server could not connect to port: " + port);
e1.printStackTrace();
System.exit(0);
}
change the code above to
#Override
public void run() {
try {
server = new ServerSocket(port);
} catch (IOException e1) {
System.out.println("Server could not connect to port: " + port);
e1.printStackTrace();
System.exit(0);
}
Related
I'm creating an "echo" server that upon receiving a message simply sends it back. I have managed to get multi-client working, but I want to make some kind of disconnect detection. I tried to get it working through sending a single character from the server, then replying with another character from the client. I couldn't get this to work, though.
How would you suggest I go about disconnect detection?
MessageServer.java
import java.net.*;
import java.io.*;
public class MessageServer {
static int clientCount = 0;
public static void main(String[] args) throws IOException {
try(ServerSocket servSocket = new ServerSocket(16384)){
while(true){
Socket socket = servSocket.accept();
addClient();
new ServerThread(socket, clientCount).start();
}
} catch(IOException e) {
System.out.println("Exception caught when trying to listen on port 16384 or listening for a connection");
System.out.println(e.getMessage());
}
}
public static void addClient(){
clientCount++;
}
}
ServerThread.java
import java.net.*;
import java.io.*;
public class ServerThread extends Thread {
private Socket cltSocket;
private BufferedReader in;
private PrintWriter out;
private int num;
public ServerThread(Socket clientSocket, int count) {
cltSocket = clientSocket;
num = count;
}
public void run() {
String input;
try {
out = new PrintWriter(cltSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(cltSocket.getInputStream()));
System.out.println("Client " + num + " connected!");
while(cltSocket.isConnected() && !cltSocket.isClosed()){
if(in.ready()){
input = in.readLine();
if(input != null && !(input.equalsIgnoreCase("exit"))){
System.out.print("New input: ");
System.out.println(input);
out.println(input);
out.flush();
} else if(input.equalsIgnoreCase("exit")){
disconnect();
}
}
}
} catch(SocketException e) {
disconnect();
} catch (IOException e) {
e.printStackTrace();
return;
}
}
public void disconnect(){
System.out.println("Client " + num + " disconnected!");
out.close();
try {
in.close();
cltSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
MessageClient.java
import java.net.*;
import java.io.*;
public class MessageClient {
public static void main(String[] args) {
if(args.length != 2) {
System.out.println("Invalid parameters! Format as: (hostname) (port)");
System.exit(1);
}
String hostname = args[0];
int port = Integer.parseInt(args[1]);
try {
Socket socket = new Socket(hostname, port);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Connected!");
while(socket.isConnected() && !socket.isClosed()){
String output;
if(con.ready()) {
output = con.readLine();
out.println(output);
if(output.equalsIgnoreCase("exit")) {
socket.close();
}
}
if(in.ready()){
String li = in.readLine();
if(li != null) {
System.out.println(li);
}
}
}
System.out.println("Disconnected!");
con.close();
out.close();
in.close();
System.exit(0);
} catch(SocketException e) {
System.err.println("Socket error:" + e);
} catch(UnknownHostException e) {
System.err.println("Invalid host");
} catch(IOException e) {
System.err.println("IO Error: " + e);
}
}
}
There is a way to do that:
if you read the BufferedReader by calling BufferedReader.getLine() and the other side socket is gone, then you get an SocketException... that is a way to check a lost connection
I am making 2 classes for Chat server client for a project I am working on. The problem is server can see the message that sent to it(from client) and it can send those messages out to every clients BUT each client has to type in some input first if he wants to see the message from other users. I have no clue what I did wrong. Please help me out. Thanks in advance :)
Server Class
import java.net.*;
import java.util.ArrayList;
import java.io.*;
public class TestServer extends Thread
{
protected Socket clientSocket;
public static ArrayList<Socket> ConnectionArray = new ArrayList<Socket>();
public static ArrayList<String> CurrentUsers = new ArrayList<String>();
final static int PORT = 22;
public static void main(String[] args) throws IOException
{
ServerSocket serverSocket = null;
try
{
serverSocket = new ServerSocket(PORT);
System.out.println ("Connection Socket Created");
try
{
while (true)
{
System.out.println ("Waiting for Connection");
Socket sock = serverSocket.accept();
ConnectionArray.add(sock);
System.out.println("Client connected from: " + sock.getLocalAddress().getHostName());
new TestServer (sock);
}
}
catch (IOException e)
{
System.err.println("Accept failed.");
System.exit(1);
}
}
catch (IOException e)
{
System.err.println("Could not listen on port: " + PORT);
System.exit(1);
}
finally
{
try {
serverSocket.close();
}
catch (IOException e)
{
System.err.println("Could not close port: 10008.");
System.exit(1);
}
}
}
private TestServer (Socket inSock)
{
clientSocket = inSock;
start();
}
public void run()
{
System.out.println ("New Communication Thread Started");
//System.out.println ("Client connected from: " + sock.getLocalAddress().getHostName());
try {
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true);
BufferedReader in = new BufferedReader(new InputStreamReader( clientSocket.getInputStream()));
String inputLine;
while (true)
{
inputLine = in.readLine();
System.out.println ("Server: " + inputLine);
for(int i = 1; i <= TestServer.ConnectionArray.size(); i++)
{
System.out.println("Total Connection: " + ConnectionArray.size());
Socket TEMP_SOCK = (Socket) TestServer.ConnectionArray.get(i-1);
if (clientSocket != TEMP_SOCK)
{
PrintWriter TEMP_OUT = new PrintWriter(TEMP_SOCK.getOutputStream(), true);
TEMP_OUT.println(inputLine);
TEMP_OUT.flush();
System.out.println("Sending to: " + TEMP_SOCK.getLocalAddress().getHostName());
}
}
if (inputLine.equals("Bye."))
break;
}
out.close();
in.close();
clientSocket.close();
}
catch (IOException e)
{
System.err.println("Problem with Communication Server");
System.exit(1);
}
}
}
Client Class
import java.io.*;
import java.net.*;
public class TestClient {
public static void main(String[] args) throws IOException {
String serverHostname = new String ("127.0.0.1");
if (args.length > 0)
serverHostname = args[0];
System.out.println ("Attemping to connect to host " +
serverHostname);
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket(serverHostname, 22);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + serverHostname);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for "
+ "the connection to: " + serverHostname);
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
System.out.println ("Type Message (\"Bye.\" to quit)");
while ((userInput = stdIn.readLine()) != null)
{
out.println(userInput);
if (userInput.equals("Bye."))
break;
System.out.println("Other user: " + in.readLine());
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
You need a separate thread in the client for reading from the server without blocking on System.in;
Thread t = new Thread(() -> {
try {
while (!Thread.currentThread().isInterrupted()) {
System.out.println("Other user: " + in.readLine());
}
} catch (Exception e) {
e.printStackTrace();
}
});
t.start();
while ((userInput = stdIn.readLine()) != null)
{
out.println(userInput);
if (userInput.equals("Bye."))
break;
}
t.interrupt();
I"m working on a Client-Server chat program for a university project and I have little programming background. I've made 3 classes: ChatClient, ChatServer and ChatServerThread. I can currently have multiple clients connected and talking to the server at any time.
Although one of the requirements that I'm having the most difficulty is this: "Any message typed from 1 client is sent to all other clients" and also "Both sent and received messages should be displayed".
I've spent the last few nights just trying to get this extra bit of functionality working but have had no luck.
I've been reading and looking around for a while but I have lots of difficulty adapting online examples to my work. I've read that I should be creating a list of sockets and then iterate through the list and send data to everyone in the list, which makes sense in my head but gives me a headache when I try implementing it. Any help with this would be very greatly appreciated. Extra points if anyone can give me some insight on how I could encrypt the sent data.
ChatClient
import java.net.*;
import java.io.*;
public class ChatClient {
private Socket socket = null;
private DataInputStream console = null;
private DataOutputStream streamOut = null;
private String myName = null;
private BufferedReader StreamIn = null;
private String response = null;
public ChatClient(String serverName, int serverPort) {
try {
console = new DataInputStream(System.in);
System.out.println("What is your name?");
myName = console.readLine();
System.out.println(myName + " <" + InetAddress.getLocalHost() + "> ");
} catch (IOException ioe) {
System.out.println("Unexpected exception: " + ioe.getMessage());
}
System.out.println("Establishing connection. Please wait ...");
try {
socket = new Socket(serverName, serverPort);
System.out.println("Connected: " + socket);
StreamIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
streamOut = new DataOutputStream(socket.getOutputStream());
streamOut.writeUTF(":" + myName + " <" + InetAddress.getLocalHost() + "> HAS JOINED");
streamOut.flush();
} catch (UnknownHostException uhe) {
System.out.println("Host unknown: " + uhe.getMessage());
} catch (IOException ioe) {
System.out.println("Unexpected exception: " + ioe.getMessage());
}
String line = "";
while (!line.equals(".bye")) {
try {
line = console.readLine();
streamOut.writeUTF(myName + " <" + InetAddress.getLocalHost() + "> : " + line);
streamOut.flush();
} catch (IOException ioe) {
System.out.println("Sending error: " + ioe.getMessage());
}
}
}
public void stop() {
try {
if (console != null) console.close();
if (streamOut != null) streamOut.close();
if (socket != null) socket.close();
} catch (IOException ioe) {
System.out.println("Error closing ...");
}
}
public static void main(String args[]) {
ChatClient client = null;
if (args.length != 2)
System.out.println("Usage: java ChatClient host port");
else
client = new ChatClient(args[0], Integer.parseInt(args[1]));
}
}
ChatServer
import java.net.*;
import java.io.*;
import java.util.*;
public class ChatServer implements Runnable {
private ServerSocket server = null;
private Thread thread = null;
private ChatServerThread client = null;
private String clientSentence = null;
private int peers = 0;
private List clients = new ArrayList();
final List sockets = new ArrayList();
public ChatServer(int port) {
try {
System.out.println("Binding to port " + port + ", please wait ...");
server = new ServerSocket(port);
System.out.println("Server started: " + server);
start();
} catch (IOException ioe) {
System.out.println(ioe);
}
}
public void run() {
while (thread != null) {
try {
System.out.println("Waiting for a client ...");
addThread(server.accept());
} catch (IOException ie) {
System.out.println("Acceptance Error: " + ie);
}
}
}
public void addThread(Socket socket) {
System.out.println("Client accepted: " + socket);
client = new ChatServerThread(this, socket);
try {
client.open();
client.start();
} catch (IOException ioe) {
System.out.println("Error opening thread: " + ioe);
}
}
public void start() {
if (thread == null) {
thread = new Thread(this);
thread.start();
}
}
public void stop() {
if (thread != null) {
thread.stop();
thread = null;
}
}
public void increment(String sentence) {
peers++;
String[] info = sentence.split(" ");
String name = info[0].replace(":", "");
System.out.println(name + " Has joined the room, we now have " + peers + " peer(s).");
clients.add(name);
}
public Boolean isAllowed(String name, Socket socket) {
try {
String stringSearch = name;
BufferedReader bf = new BufferedReader(new FileReader("allowed.txt"));
int linecount = 0;
String line = "";
System.out.println("Searching for " + stringSearch + " in file...");
while ((line = bf.readLine()) != null) {
linecount++;
String[] words = line.split(" ");
for (String word : words) {
if (word.equals(stringSearch)) {
System.out.println("User is allowed");
registerSocket(socket);
return true;
}
}
}
bf.close();
} catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
System.out.println("User is not allowed");
return false;
}
public void showAll() {
for (int i = 0; i < clients.size(); i++) {
System.out.print(clients.get(i));
}
}
public void registerSocket(Socket socket) {
//socket = new DataOutputStream(socket.getOutputStream());
sockets.add(socket);
for (int i = 0; i < sockets.size(); i++) {
System.out.println(sockets.get(i));
}
}
public static void main(String args[]) {
ChatServer server = null;
if (args.length != 1)
System.out.println("Usage: java ChatServer port");
else
server = new ChatServer(Integer.parseInt(args[0]));
}
}
ChatServerThread
import java.net.*;
import java.io.*;
public class ChatServerThread extends Thread {
private Socket socket = null;
private ChatServer server = null;
private int ID = -1;
private DataInputStream streamIn = null;
private String clientSentence = null;
public String newGuy = null;
DataOutputStream streamOut = null;
public ChatServerThread(ChatServer _server, Socket _socket) {
server = _server;
socket = _socket;
ID = socket.getPort();
}
public void run() {
System.out.println("Server Thread " + ID + " running.");
while (true) {
try {
String sentence = streamIn.readUTF();
//System.out.println(sentence);
char c = sentence.charAt(0);
String[] command = null;
command = sentence.split(" ");
String name = command[0].substring(1);
System.out.println("Sending out: " + sentence + " via ");
streamOut.writeBytes(sentence);
if (c == ':') {
if (server.isAllowed(name, socket))
server.increment(sentence);
else {
close();
}
}
} catch (IOException ioe) {
}
}
}
public void open() throws IOException {
streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
}
public void close() throws IOException {
if (socket != null) socket.close();
if (streamIn != null) streamIn.close();
}
}
I'm trying to setup a client server application using socket programming. My client connects to the server, but I'm unable to get the multiple event handling to work. My client applet has two text boxes and buttons associated with each one of of them. When I click button one, I was trying to get "Hello" to be displayed in the text box. When I click on button two, I was trying to get "Hello there" to be displayed in the second text box. However, only one value (the value I first click) shows up in both of the text boxes. Is my event handling mechanism incorrect? I am implementing the serializable interface and the client server communication deals with objects. Can someone please tell me what the problem in the code is? I haven't posted the ObjectCommunication.java code, but it simply implements the serializable interface and has the getter and setter (takes a string as an input parameter) method.
Many thanks!
The following is my server code:
import java.io.*;
import java.net.*;
public class Server_App {
public static void main(String[] args) {
try {
ServerSocket holder = new ServerSocket(4500);
for (;;) {
Socket incoming = holder.accept();
new ServerThread(incoming).start();
}
} catch (Exception e) {
System.out.println(e);
}
}
}
class ServerThread extends Thread
{
public ServerThread(Socket i) {
incoming = i;
}
public void run() {
try {
ObjectCommunication hold = new ObjectCommunication();
ObjectInputStream input = new ObjectInputStream(incoming.getInputStream());
ObjectOutputStream output = new ObjectOutputStream(incoming.getOutputStream());
hold = (ObjectCommunication) input.readObject();
if ((hold.getMessage()).equals("Event 1")) {
System.out.println("Message read: " + hold.getMessage());
hold.setMessage("Hello!");
} else if ((hold.getMessage()).equals("Event 2")) {
System.out.println("Message read:" + hold.getMessage());
hold.setMessage("Hello there!");
}
output.writeObject(hold);
input.close();
output.close();
incoming.close();
} catch (Exception e) {
System.out.println(e);
}
}
ObjectCommunication hold = null;
private Socket incoming;
}
The following is the client code:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class Client_App extends Applet {
TextField textVal;
TextField anotherTextVal;
Socket socket;
ObjectCommunication hold = new ObjectCommunication();
ObjectCommunication temp = new ObjectCommunication();
ObjectOutputStream OutputStream;
ObjectInputStream InputStream;
public void init() {
socketConnection();
createGUI();
validate();
}
public void socketConnection() {
try {
socket = new Socket("127.0.0.1", 4500);
} catch (Exception e) {
System.out.println("Unknown Host");
}
try {
OutputStream = new ObjectOutputStream(socket.getOutputStream());
InputStream = new ObjectInputStream(socket.getInputStream());
} catch (IOException ex) {
System.out.println("Error: " + ex);
return;
}
}
public void createGUI() {
Button button = new Button("Hello Button");
add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
button_actionPerformed(evt);
}
});
textVal = new TextField(6);
add(textVal);
Button anotherButton = new Button("Hello there Button");
add(anotherButton);
anotherButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
anotherButton_actionPerformed(evt);
}
});
anotherTextVal = new TextField(6);
add(anotherTextVal);
}
public void button_actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
if (e.getSource() instanceof Button)
if (actionCommand.equals("Hello Button")) {
try {
temp.setMessage("Event 1");
//OutputStream.writeObject(temp);
new SendToServer().start();
new ListenToServer().start();
} catch (Exception ex) {
System.out.println("Communication didn't work!");
}
textVal.setText(hold.getMessage());
}
}
public void anotherButton_actionPerformed(ActionEvent evt) {
String action_Command = evt.getActionCommand();
if (evt.getSource() instanceof Button)
if (action_Command.equals("Hello there Button")) {
try {
temp.setMessage("Event 2");
new SendToServer().start();
new ListenToServer().start();
} catch (Exception ex) {
System.out.println("Communication didn't work!");
}
anotherTextVal.setText(hold.getMessage());
}
}
class ListenToServer extends Thread {
public void run() {
while (true) {
try {
hold = (ObjectCommunication) InputStream.readObject();
} catch (IOException e) {} catch (ClassNotFoundException e2) {}
}
}
}
class SendToServer extends Thread {
public void run() {
while (true) {
try {
OutputStream.writeObject(temp);
} catch (IOException e) {}
}
}
}
}
To be honest - I'm a little bit lazy to read through your code and seek there for a bug :) Nevertheless I'll post you here my snippet for socket-based multiple client-server application..
import java.net.*;
import java.io.*;
class ServeConnection extends Thread {
private Socket socket = null;
private BufferedReader in = null;
private PrintWriter out = null;
public ServeConnection(Socket s) throws IOException {
// init connection with client
socket = s;
try {
in = new BufferedReader(new InputStreamReader(
this.socket.getInputStream()));
out = new PrintWriter(this.socket.getOutputStream(), true);
} catch (IOException e) {
System.err.println("Couldn't get I/O.");
System.exit(1);
}
start();
}
public void run() {
System.out.println("client accepted from: " + socket.getInetAddress()
+ ":" + socket.getPort());
// get commands from client, until is he communicating or until no error
// occurs
String inputLine, outputLine;
try {
while ((inputLine = in.readLine()) != null) {
System.out.println("request: " + inputLine);
outputLine = inputLine;
out.println("I've recived "+outputLine);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("server ending");
out.close();
try {
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Server {
public static void svr_main(int port) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(port);
} catch (IOException e) {
System.err.println("Could not listen on port: " + port);
System.exit(1);
}
System.out.println("Server ready");
try {
while (true) {
Socket socket = serverSocket.accept();
try {
new ServeConnection(socket);
} catch (IOException e) {
System.err.println("IO Exception");
}
}
} finally {
serverSocket.close();
}
}
}
class Client {
static Socket echoSocket = null;
static PrintWriter out = null;
static BufferedReader in = null;
public static void cli_main(int port, String servername) throws
IOException {
try {
echoSocket = new Socket(servername, port);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " + servername);
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O for " + servername);
System.exit(1);
}
System.out.println("Client ready!");
while (true) {
inputLine = (in.readLine().toString());
if (inputLine == null) {
System.out.println("Client closing!");
break;
}
// get the input and tokenize it
String[] tokens = inputLine.split(" ");
}
out.close();
in.close();
echoSocket.close();
System.out.println("Client closing");
}
}
public class MyClientServerSnippet{
public static void main(String[] args) throws IOException {
if (args.length == 0) {
System.err.println("Client: java snippet.MyClientServerSnippet<hostname> <port>");
System.err.println("Server: java snippet.MyClientServerSnippet<port>");
System.exit(1);
}
else if (args.length > 1) {
System.out.println("Starting client...\n");
Client client = new Client();
client.cli_main(3049, "127.0.0.1");
} else {
System.out.println("Starting server...\n");
Server server = new Server();
server.svr_main(3049);
}
}
}
Hope this helps :] If anything would be ununderstandable, don't hesitate to ask for more details :)
I am learning Java and want to create my own IRC client. I have two threads but the problem is that I do not always get a response from server (can't see PING) and it lags for my message to be delivered.
I thought it was related to thread not having a sleep, but it turns out it's not.
When I connect to the server I send the following commands to identify myself and privatemsg self:
USER me * 8 : hi
NICK mynick
I am also not sure if my usage of threads is correct.
The code I used:
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class f_irc {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
Socket ircSocket = null;
BufferedWriter out = null;
BufferedReader in = null;
String host = "irc.freenode.net";
int port = 6667;
Boolean proxyEnabled = true;
try {
SocketAddress addr = new InetSocketAddress("127.0.0.1", 1080);
Proxy proxy = new Proxy(Proxy.Type.SOCKS, addr);
ircSocket = new Socket(proxy);
InetSocketAddress final_addr = new InetSocketAddress(host, port);
ircSocket.connect(final_addr);
}
catch(Exception e)
{
ircSocket = new Socket(host, port);
}
Thread listener = new ServerListener(ircSocket);
listener.start();
System.out.println("Listener started!");
Thread sender = new ServerSender(ircSocket);
sender.start();
System.out.println("Sender started!");
}
}
class ServerListener extends Thread implements Runnable {
Socket ircSocket;
String serverAnswer = null;
BufferedReader in = null;
ServerListener(Socket irc) throws IOException {
ircSocket = irc;
in = new BufferedReader(new InputStreamReader(irc.getInputStream()));
}
#Override
public void run() {
while(true) {
System.out.println("Running: ");
try {
serverAnswer = in.readLine();
if (serverAnswer != null) {
System.out.println("Server talkin: " + in.readLine());
System.out.println("Server talkin++: " + serverAnswer);
}
} catch (IOException ex) {
System.out.println("cant read linez br0w");
}
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
Logger.getLogger(ServerSender.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
class ServerSender extends Thread {
Socket ircSocket;
String serverCommand = null;
BufferedWriter out = null;
BufferedReader stdIn = null;
ServerSender(Socket irc) throws IOException {
ircSocket = irc;
out = new BufferedWriter(new OutputStreamWriter(irc.getOutputStream()));
stdIn = new BufferedReader(new InputStreamReader(System.in));
}
#Override
public void run() {
while(true) {
System.out.println("Running snder: ");
try {
serverCommand = stdIn.readLine();
if (serverCommand != null) {
out.write(serverCommand + "\n");
out.flush();
System.out.println("Sent: " + serverCommand);
}
}
catch(IOException e) {
System.out.println("Server fed up");
}
try {
Thread.sleep(100);
} catch (InterruptedException ex) {
System.out.println("Sleep failed!");
}
}
}
}
you are calling in.readLine() twice in your ServerListener. since you are consuming 2 messages per-loop, will not see any output until you get an even number of messages (so the 3rd message will seem to "hang" until you get the fourth).