I have two classes - Provider and Requester:
Provider
import java.io.*;
import java.net.*;
public class Provider {
ServerSocket providerSocket;
Socket connection = null;
ObjectOutputStream out;
ObjectInputStream in;
String message;
Provider() {
}
void run() {
try {
// 1. creating a server socket
providerSocket = new ServerSocket(2004, 10);
// 2. Wait for connection
System.out.println("Waiting for connection");
connection = providerSocket.accept();
System.out.println(
"Connection received from " + connection.getInetAddress().getHostName());
// 3. get Input and Output streams
out = new ObjectOutputStream(connection.getOutputStream());
out.flush();
in = new ObjectInputStream(connection.getInputStream());
sendMessage("Connection successful");
// 4. The two parts communicate via the input and output streams
do {
try {
sendMessage(
"Please enter the phrase you wish to echo or the word FINISHED to exit");
message = (String) in.readObject();
sendMessage(message);
} catch (ClassNotFoundException classnot) {
System.err.println("Data received in unknown format");
}
} while (!message.equals("FINISHED"));
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
// 4: Closing connection
try {
in.close();
out.close();
providerSocket.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
void sendMessage(String msg) {
try {
out.writeObject(msg);
out.flush();
System.out.println("server>" + msg);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
public static void main(String args[]) {
Provider server = new Provider();
while (true) {
server.run();
}
}
}
Requester
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class Requester {
Socket requestSocket;
ObjectOutputStream out;
ObjectInputStream in;
String message;
Scanner input;
Requester() {
input = new Scanner(System.in);
}
void run() {
try {
// 1. creating a socket to connect to the server
requestSocket = new Socket("127.0.0.1", 2004);
System.out.println("Connected to localhost in port 2004");
// 2. get Input and Output streams
out = new ObjectOutputStream(requestSocket.getOutputStream());
out.flush();
in = new ObjectInputStream(requestSocket.getInputStream());
// 3: Communicating with the server
try {
message = (String) in.readObject();
System.out.println("server>" + message);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
do {
try {
message = (String) in.readObject();
System.out.println(message);
message = input.nextLine();
sendMessage(message);
message = (String) in.readObject();
} catch (ClassNotFoundException classNot) {
System.err.println("data received in unknown format");
}
} while (!message.equals("FINISHED"));
} catch (UnknownHostException unknownHost) {
System.err.println("You are trying to connect to an unknown host!");
} catch (IOException ioException) {
ioException.printStackTrace();
} finally {
// 4: Closing connection
try {
in.close();
out.close();
requestSocket.close();
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
}
void sendMessage(String msg) {
try {
out.writeObject(msg);
out.flush();
System.out.println("client>" + msg);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
public static void main(String args[]) {
Requester client = new Requester();
client.run();
}
}
The programs are basically meant to communicate with each other. The idea is that they each 'connect' with each other via sockets and the user should be able to enter something in the console window of Provider and have it echoed back onto the console of Requester. However, I am getting the following errors:
Provider
java.net.SocketException: Permission denied: listen failed
Requester
java.net.ConnectException: Connection refused: connect
(I can provide the rest of the errors if it would help in fixing the issue).
I have tried having the classes in the same project folder, in separate folders, and in different workspaces. I have also tried using Eclipse EE (Neon) and the SE (Oxygen). Recently, I have been having problems with ports and sockets (most notably with Tomcat and encountering the 'Cannot find free socket for debugger' in Eclipse). Would that have something to do with me being unable to run these programs?
Check your firewall settings. I was having similar problems when trying to use sockets. Make sure any relevant resources aren't blocked.
You might also want to run the command:
netstat -ano | findstr :2004
to check if that port is mistakenly in use already.
first of all, I'm rather new to socket programming to go easy on me ;).
I have a Java program that uses client-server programming to communicate between 1 or more clients and the server. So the clients can send any number of messages to the server where the messages are dealt with and all is fine so far. Now I want to notify the clients of e.g. database changes on the server side. So for example if one client changes for example table A, the other clients should also be notified about this change.
What I have so far is the following (server):
ExecutorService executor = null;
try (ServerSocket socket = new ServerSocket(port);)
{
executor = Executors.newFixedThreadPool(getThreadCount(5));
while(true)
{
Socket clientSocket = socket.accept();
Runnable worker = new PCRequestMapper(clientSocket);
executor.execute(worker);
}
}
catch(IOException ioe)
{
ioe.printStackTrace();
}
finally
{
if(executor != null)
{
executor.shutdown();
}
}
The request mapper class then looks like this:
public class PCRequestMapper implements Runnable
{
private Socket client = null;
private static Map<Integer, PCRequestData> requestData = null;
public PCRequestMapper(Socket client)
{
this.client = client;
}
#Override
public void run()
{
try (ObjectInputStream in = new ObjectInputStream(
client.getInputStream());
ObjectOutputStream writer = new ObjectOutputStream(
client.getOutputStream());)
{
System.out.println("Thread started in PCRequestHandler with name: "
+ Thread.currentThread().getName());
Object recObj = in.readObject();
// ToDo Do something
PCBaseRequest req = (PCBaseRequest) recObj;
System.out.println("Req type: " + req.getRequestType() + " name: "
+ req.getName());
PCRequestData data = requestData.get(req.getRequestType());
if(data == null)
{
PCException ex = new PCException();
ex.setStackTrace(new Throwable().getStackTrace());
PCBaseReply reply = getErrorReply("No mapped request handler found in services.xml for request: "+req.getRequestType()+" - "+req.getName(),
PCException.NO_MAPPED_HANDLER, ex);
writer.writeObject(reply);
}
else
{
Class<?> c = Class.forName(data.getMappedClass());
Constructor<?> cons = c.getConstructor();
PCIRequestHandler object = (PCIRequestHandler)cons.newInstance();
PCBaseReply reply = object.heyHo(req);
System.out.println("Writing reply: "+reply.getClass());
writer.writeObject(reply);
}
} catch (IOException ioe)
{
ioe.printStackTrace();
} catch (ClassNotFoundException cnfe)
{
cnfe.printStackTrace();
} catch (NoSuchMethodException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
It basically takes a message (request), maps it to a configured class and then that class performs whatever action needed.
On the client side, I have a class called RequestSender, which is used to send arbitrary requests to the server:
public class PCRequestSender
{
private static int getPort(int defaultPort)
{
final String port = PCConfigHandler.getStringProperty("serverPort");
if (null != port)
{
try
{
return Integer.parseInt(port);
} catch (NumberFormatException e)
{
System.out.println("Value of port property"
+ " is not a valid positive integer [" + port + "]."
+ " Reverting to default [" + defaultPort + "].");
}
}
return defaultPort;
}
public static PCBaseReply sendRequest(PCBaseRequest req)
{
PCBaseReply reply = null;
int port = getPort(8081);
String address = PCConfigHandler.getStringProperty("serverAddress");
try (Socket serverSocket = new Socket(address, port);
ObjectOutputStream out = new ObjectOutputStream(
serverSocket.getOutputStream());
ObjectInputStream in = new ObjectInputStream(
serverSocket.getInputStream());)
{
out.writeObject(req);
Object recObj = in.readObject();
reply = (PCBaseReply) recObj;
System.out.println("Reply: "+reply);
} catch (IOException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e)
{
e.printStackTrace();
}
return reply;
}
}
Now I'm a bit at a loss, because I would also like to constantly listen to a server socket to catch notifications. Do I need another socket on the server side? Is my setup not tooooo ideal?
I'm helpful for any hints...thanks!
I have a problem with socket communication.
Sometimes reading from inputstream on client side stops working while the server is still sending new messages. I debugged the server so I know that is still working and sending messages to the outputstream. But on the client side read from inputstream is blocked. I can't debug this situation on client side. I only see difference in received messages on client side just before everything stops.
Example of good received message when everything works fine. Single send message in one line (I use DataInputStream.readUTF() method on client side and DataOutputStream.writeUTF(String msg) on server side. )
ADD;MB57,18-9,5,dd,10,10;
UP;MB15;20;14;20;13;1.0;
ADD;MB37,18-9,5,xx,10,10;
UP;MB13;20;14;20;13;1.0;
ADD;MB47,18-9,5,ww,10,10;
UP;MB13;20;14;20;13;1.0;
And this is happens just before my socket stop reading from input. One big mess. And everything that has been sent from the beginning in one line. It looks like the buffer overload O.o What happens?
11-07 11:36:41.978: I/System.out(17980): 11;8;10;8;0.1;��UPPOS;MB8;16;8;16;7;1.0;��PATH;MB8��UPPOS;MB20;14;9;14;10;1.0;�� ADDMOB;MB20,14-10,6,mummy,50,50;�� PATH;MB20��UPPOS;MB50;12;8;12;7;1.0;�� PATH;MB50��UPPOS;MB13;15;11;14;11;1.0;�� PATH;MB19��PATH;MB8��UPPOS;MB20;14;10;13;10;1.0;�� PATH;MB20��UPPOS;MB50;12;7;12;6;1.0;�� PATH;MB50��UPPOS;MB13;14;11;14;10;1.0;��UPPOS;MB19;13;9;14;9;1.0;�� PATH;MB19��PATH;MB8��UPPOS;MB20;13;10;13;9;1.0;��ADDMOB;MB20,13-9,6,mummy,50,50;�� PATH;MB20��UPPOS;MB50;12;6;12;7;1.0;�� PATH;MB50��UPPOS;MB13;14;10;15;9;1.0;��!ADDMOB;MB13,15-9,5,chicken,10,10;�� PATH;MB13��UPPOS;MB19;14;9;14;10;1.0;��!ADDMOB;MB19,14-10,1,goblin,37,50;�� PATH;MB19��UPPOS;NP12;10;8;9;8;0.1;��UPPOS;MB8;16;7;17;7;1.0;��PATH;MB8��UPPOS;MB20;13;9;12;9;1.0;�� PATH;MB20��UPPOS;MB50;12;7;11;7;1.0;�� PATH;MB50��UPPOS;MB13;15;9;14;9;1.0;�� PATH;MB13��UPPOS;MB19;14;10;13;9;1.0;�� ADDMOB;MB19,13-9,1,goblin,37,50;�� PATH;MB19��UPPOS;MB8;17;7;16;7;1.0;��PATH;MB8��UPPOS;MB20;12;9;12;8;1.0;��UPPOS;MB50;11;7;12;7;1.0;�� PATH;MB50��UPPOS;MB13;14;9;14;10;1.0;��"ADDMOB;MB13,14-10,5,chicken,10,10;�� PATH;MB13�� PATH;MB19��UPPOS;MB8;16;7;16;8;1.0;��PATH;MB8�� PATH;MB20�� PATH;MB50��UPPOS;MB13;14;10;15;10;1.0;�� PATH;MB13��UPPOS;MB19;13;9;14;9;1.0;�� PATH;MB19��UPPOS;NP12;9;8;9;9;0.1;��UPPOS;MB8;16;8;16;7;1.0;��PATH;MB8��UPPOS;MB20;12;8;12;9;1.0;�� PATH;MB20��UPPOS;MB50;12;7;12;6;1.0;�� PATH;MB50��UPPOS;MB13;15;10;14;10;1.0;��UPPOS;MB19;14;9;13;9;1.0;�� PATH;MB19��PATH;MB8��UPPOS;MB20;12;9;12;8;1.0;�� PATH;MB50��UPPOS;MB13;14;10;14;9;1.0;��!ADDMOB;MB13,14-9,5,chicken,10,10;�� PATH;MB13�� PATH;MB19��UPPOS;MB8;16;7;16;6;1.0;��PATH;MB8��UPPOS;MB20;12;8;12;7;1.0;�� PATH;MB20�� PATH;MB50��UPPOS;MB13;14;9;14;10;1.0;��"ADDMOB;MB13,14-10,5,chicken,10,10;�� PATH;MB13��UPPOS;MB19;13;9;13;10;1.0;��!ADDMOB;MB19,13-10,1,goblin,37,50;�� PATH;MB19��UPPOS;NP12;9;9;9;8;0.1;��PATH;MB8�� PATH;MB20��UPPOS;MB50;12;6;11;6;1.0;�� PATH;MB50��UPPOS;MB13;14;10;14;9;1.0;��!ADDMOB;MB13,14-9,5,chicken,10,10;�� PATH;MB13��UPPOS;MB19;13;10;13;9;1.0;�� ADDMOB;MB19,13-9,1,goblin,37,50;�� PATH;MB19��UPPOS;MB8;16;6;16;7;1.0;��PATH;MB8�� PATH;MB20��UPPOS;MB50;11;6;12;6;1.0;�� PATH;MB50��UPPOS;MB13;14;9;15;9;1.0;�� PATH;MB13�� PATH;MB19��PATH;MB8��UPPOS;MB20;12;7;12;8;1.0;�� PATH;MB20�� PATH;MB50��UPPOS;MB13;15;9;14;9;1.0;�� PATH;MB13��UPPOS;MB19;13;9;13;10;1.0;��!ADDMOB;MB19,13-10,1,goblin,37,50;�� PATH;MB19��UPPOS;NP12;9;8;10;8;0.1;��UPPOS;MB8;16;7;16;8;1.0;��PATH;MB8��UPPOS;MB20;12;8;12;7;1.0;�� PATH;MB20�� PATH;MB50��UPPOS;MB13;14;9;15;9;1.0;�� PATH;MB13��UPPOS;MB19;13;10;13;11;1.0;�� PATH;MB19��UPPOS;MB8;16;8;16;9;1.0;��PATH;MB8��UPPOS;MB20;12;7;11;7;1.0;�� PATH;MB20��UPPOS;MB13;15;9;14;9;1.0;�� PATH;MB50�� PATH;MB13��UPPOS;MB19;13;11;13;10;1.0;��UPPOS;MB20;11;7;12;7;1.0;�� PATH;MB20��UPPOS;MB8;16;9;16;8;1.0;�� PATH;MB50��UPPOS;MB13;14;9;15;9;1.0;�� PATH;MB13��UPPOS;MB19;13;10;14;10;1.0;��UPPOS;NP12;10;8;11;8;0.1;�� PATH;MB20��UPPOS;MB8;16;8;16;7;1.0;��PATH;MB8�� PATH;MB50��UPPOS;MB13;15;9;14;9;1.0;�� PATH;MB13��UPPOS;MB19;14;10;15;9;1.0;�� ADDMOB;MB19,15-9,1,goblin,37,50;�� PATH;MB19��UPPOS;MB20;12;7;11;7;1.0;�� PATH;MB20��UPPOS;MB8;16;7;16;6;1.0;��PATH;MB8��UPPOS;MB50;12;6;12;7;1.0;�� PATH;MB50��UPPOS;MB13;14;9;13;9;1.0;�� PATH;MB13��UPPOS;MB19;15;9;14;9;1.0;�� PATH;MB19�� PATH;MB20��UPPOS;MB8;16;6;16;7;1.0;��PATH;MB8��UPPOS;MB50;12;7;12;8;1.0;�� PATH;MB50�� PATH;MB13��UPPOS;MB19;14;9;14;10;1.0;��!ADDMOB;MB19,14-10,1,goblin,37,50;�� PATH;MB19��UPPOS;MB20;11;7;12;7;1.0;�� PATH;MB20��UPPOS;MB8;16;7;16;8;1.0;��PATH;MB8��UPPOS;MB50;12;8;12;9;1.0;�� PATH;MB50��UPPOS;MB13;13;9;14;9;1.0;�� PATH;MB13��UPPOS;MB19;14;10;15;10;1.0;�� PATH;MB19��UPPOS;MB20;12;7;11;7;1.0;�� PATH;MB20��UPPOS;MB50;12;9;12;8;1.0;�� PATH;MB50��UPPOS;MB8;16;8;16;7;1.0;��PATH;MB8��UPPOS;MB13;14;9;13;9;1.0;�� PATH;MB13��UPPOS;MB19;15;10;15;9;1.0;�� ADDMOB;MB19,15-9,1,goblin,37,50;��UPPOS;NP12;11;8;10;8;0.1;��UPPOS;MB20;11;7;12;7;1.0;��UPPOS;MB8;16;7;16;6;1.0;��PATH;MB8�� PATH;MB13��UPPOS;MB50;12;8;11;8;1.0
Client side
private DataOutputStream out;
private Socket client;
private DataInputStream in;
private Thread inputListener;
public void createConnection(){
try {
client = new Socket(serverName, port);
setOut(new DataOutputStream(client.getOutputStream()));
in = new DataInputStream(client.getInputStream());
inputListener=new Thread(){
public void run(){
try {
synchronized(in){
while(client!=null){
try{
String read = new String(in.readUTF());
/** do somethink with input msg */
} catch (java.io.UTFDataFormatException e1) {
e1.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
} finally{
reconnect();
}
}
};
inputListener.start();
} catch (Exception e) {
e.printStackTrace();
}
}
private void reconnect() {
try {
client.close();
client=null;
inputListener.interrupt();
setOut(null);
in.close();
in=null;
} catch (IOException e) {
e.printStackTrace();
} finally{
System.out.println("RECONECT METHOD IN SOCKET");
}
}
Server side
private DataOutputStream out;
private Socket client;
public Client(Socket client) {
try {
setOut(new DataOutputStream(client.getOutputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendMessage(String string) {
try {
getOut().writeUTF(string);
} catch (IOException e) {
e.printStackTrace();
disconected();
}
}
You must be writing something else to the stream. Catching and ignoring UTFDataFormatException is no solution. Once you get it, you will never get back into sync with the sender.
NB Converting the result of readUTF() to a String is futile. It already is a String.
I'm trying to change my game to use TCP, but I can't even get it to work.
The client connects successfully with the server, but for some reason I can't
receive messages from server nor receive messages from client. My guess is that I'm doing something wrong with the output/input?
Here is the server code:
public class Server implements Runnable {
Server() {
serverSocket = new ServerSocket(1919, 300);
}
run() {
while (true) {
String message = "blank";
try {
//w8ting for some connection
tcpSOCKET = tcpServer.accept(null);
//Connected to some1!
input = new BufferedReader(new InputStreamReader(
tcpSOCKET.getInputStream()));
output = new DataOutputStream(
tcpSOCKET.getOutputStream());
output.flush();
//TODO PROBLEM it stays here trying to read line but even if the client send a message it wont move on
message = input.readLine();
main.addLabel(Color.BLUE, message);
} catch (EOFException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And this is the client:
public class Client implements Runnable {
Client() { }
run() {
String message = "";
try {
tcpSOCKET = new Socket(serverIp, serverTCPport);
input = new BufferedReader(new InputStreamReader(
tcpSOCKET.getInputStream()));
output = new DataOutputStream(tcpSOCKET.getOutputStream());
output.flush();
while (true) {
System.out.println("w8ting for message from server");
//TODO problem, it wont read anything even if the server send a message
message = input.readLine();
System.out.println("A message has arrived: " + message);
gameScreen.serverMessage = message;
}
} catch (EOFException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
and the class is called when I hit "s" in the server or in the client, they both use the same class
public void sendTCPMessage(String message) {
try {
output.writeBytes(message);
output.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
If you want to read lines, you must write lines.
If you want to read with a BufferedReader, you should write with a BufferedWriter.
If you want to write with a DataOutputStream, you should read with a DataInputStream.
I'm trying to send a stream of Strings from a Java server to a C++/CLI Client, but before doing that I wanted to start with the simplest case, i.e. send a single String from a Java Server to a C++/CLI client and display it.
The examples I found in the literature or in tutorials didn't work for me, knowing that the same Java Server communicated easily with another Java Client (either on the same machine or on different machines).
Without further ado, here's my Code:
the Java Server Side: SendStringToCpp.java
import java.net.*;
import java.io.*;
public class SendStringToCpp {
public static void main(String[] args) {
String message = "message"; // The String that contains the information
byte[] sentBytes = message.getBytes();
System.out.println("Message: " + message);
ServerSocket s = null;
try {
s = new ServerSocket(30011);
} catch (IOException e) {
e.printStackTrace();
}
Socket s1 = null;
try {
s1 = s.accept();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
OutputStream s1out = null;
try {
s1out = s1.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
DataOutputStream dos = new DataOutputStream (s1out);
try {
//dos.writeUTF(message); // Sending the String
dos.write(sentBytes); // Sending the bytes
} catch (IOException e) {
e.printStackTrace();
}
try {
dos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
s1out.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
s1.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
s.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The C++ Client Side: ReceiveStringFromJava.cpp
#include "stdafx.h"
#include <exception>
using namespace System;
using namespace System::Net;
using namespace System::Net::Sockets;
using namespace System::Text;
using namespace System::IO;
int main(array<System::String ^> ^args)
{
Console::WriteLine(L"Creating the Socket...");
try {
//Socket^ listener = gcnew Socket(AddressFamily::InterNetwork, SocketType::Dgram, ProtocolType::Udp);
//Creates a UdpClient for reading incoming data.
UdpClient^ receivingUdpClient = gcnew UdpClient();
IPEndPoint^ RemoteIpEndPoint = gcnew IPEndPoint(IPAddress::Any, 30011);
//listener->Bind(RemoteIpEndPoint);
array <Byte>^ receiveBytes = receivingUdpClient->Receive(RemoteIpEndPoint); // get the Bytes array from the end poitn
String^ receivedString = Encoding::ASCII->GetString(receiveBytes); // retrieve the string from the received Bytes
Console::WriteLine("This is the message received {0}", receivedString);
// Console::WriteLine("this message was send from {0} on their ort number {1}", RemoteIpEndPoint->Address, RemoteIpEndPoint->Port);
}
catch (Exception^ e) {
Console::WriteLine("Error! ");
Console::WriteLine( e->ToString());
}
Console::ReadLine();
return 0;
}
And Here's the Exception printed on the Console:
http://i.stack.imgur.com/uTDqm.jpg
P.S. I tried to Bind the IPEndPoint to the Socket (it's commented above), but to no avail, and gave the same Error.
Socket^ listener = gcnew Socket(AddressFamily::InterNetwork, SocketType::Dgram, ProtocolType::Udp);
.
.
listener->Bind(RemoteIpEndPoint);
You need to use the UdpClient constructor that allows binding to a listening port.
Quoting MSDN (emphasis mine):
Initializes a new instance of the UdpClient class and binds it to the
local port number provided.
UdpClient^ receivingUdpClient = gcnew UdpClient(30011);
// specify the port both here ^^^^^ and here vvvvv
IPEndPoint^ RemoteIpEndPoint = gcnew IPEndPoint(IPAddress::Any, 30011);
array <Byte>^ receiveBytes = receivingUdpClient->Receive(RemoteIpEndPoint);