I am trying to connect to the tcp client and I keep getting ioexception connection refused error. I don't know what I am doing wrong. I am trying to enable tcp notification. I am connecting to a rfid reader and trying to get the data back to my program to insert in a database.
Here is my code:
Socket tagServerSocket;
while (true){
try{
String data;
tagServerSocket = new Socket("localhost", this.notifyPort);
DataOutputStream outToServer = new
DataOutputStream(tagServerSocket.getOutputStream());
while (true) {
try {
Thread.sleep(20);
} catch (Exception e) {
System.err.println(e.getMessage());
}
int cnt_rd=0;
while((cnt_rd < 10) && (TagBuffer.size() > 0))
{
synchronized (TagBuffer) {
if (TagBuffer.size() != 0) {
data = "";
TagInfo tag = TagBuffer.peek();
data += "ReaderIP:" + tag.ipaddr;
data += "|ID:" + tag.epc;
data += "|Antenna:" + tag.antennaPort;
data += "|Timestamp:" + tag.timestamp;
data += "|PC:" + tag.pc;
data += "|RSSI:" + tag.rssi + "\n";
TagBuffer.remove();
outToServer.writeBytes(data);
cnt_rd++;
}
}
}
}
tagServerSocket.close();
tagServerSocket = null;
Thread.sleep(10);
startup=true;
} catch (UnknownHostException e) {
tagServerSocket = null;
startup=false;
System.out.println("Unable to connect to port " +
this.notifyPort);
} catch (IOException e) {
// tagServerSocket = null;
startup=false;
String data1 = String.format("00");
System.out.println("Unable to send tag data to server" +
data1);
System.out.println("ioexception tcpclient:
"+e.getMessage());
} catch (InterruptedException e) {
startup=false;
e.printStackTrace();
}
}
Related
I made a multiplayer snake game which is sending the actual score and health to the opponent over socket. The problem is during the game, the enemies health will be its score.
Example the enemy has 90 health and 15 score. When the enemy get 1 score it health will be 16 and the score remains 15. I think the problem is somewhere in the server:
private boolean listenForServerRequest() {
Socket socket = null;
try {
socket = serverSocket.accept();
dos = new DataOutputStream(socket.getOutputStream());
dos2 = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
dis2 = new DataInputStream(socket.getInputStream());
accepted = true;
System.out.println("Client has requested and joined the game");
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
private boolean connect() {
try {
socket = new Socket(ip, port);
dos = new DataOutputStream(socket.getOutputStream());
dos2 = new DataOutputStream(socket.getOutputStream());
dis = new DataInputStream(socket.getInputStream());
dis2 = new DataInputStream(socket.getInputStream());
accepted = true;
} catch (IOException e) {
System.out.println("Unable to connect to the address: " + ip + ":" + port + " | Starting a server");
return false;
}
System.out.println("Successfully connected to the server.");
return true;
}
private void initializeServer() {
try {
serverSocket = new ServerSocket(port, 8, InetAddress.getByName(ip));
} catch (Exception e) {
e.printStackTrace();
}
}
public boolean getConnected() {
return this.connected;
}
public void sendHealth(SnakeHead snakeHead) {
try {
dos.writeInt(snakeHead.getHealth());
System.out.println(snakeHead.getHealth());
dos.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendScore(SnakeHead snakeHead) {
try {
dos2.writeInt(Globals.getScore());
System.out.println(snakeHead.getHealth());
dos2.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public int getEnemyHealth() {
try{if (dis.available() != 0 ) {
try {
enemyHealth = dis.readInt();
return enemyHealth;
} catch (IOException e) {
e.printStackTrace();
}
}}catch (IOException e){
e.printStackTrace();
}
return enemyHealth;
}
public int getEnemyScore() {
try{if (dis2.available() != 0) {
try {
enemyScore = dis2.readInt();
return enemyScore;
} catch (IOException e) {
e.printStackTrace();
}
}}catch (IOException e){
e.printStackTrace();
}
return enemyScore;
}
Hope someone will find the problem or has any advice! Thanks!
Sending multiple data is not a problem. Socket works in TCP mode in this example so write order = read order. To avoid serialization, I would suggest you to send separated values in form of String and use PrintWriter for this purpose. This would send data in "one shot"
See this example:
try (
Socket echoSocket = new Socket(hostName, portNumber);
PrintWriter out =
new PrintWriter(echoSocket.getOutputStream(), true);
BufferedReader in =
new BufferedReader(
new InputStreamReader(echoSocket.getInputStream()));
// reading
String userInput;
while ((userInput = stdIn.readLine()) != null) {
System.out.println("echo: " + in.readLine());
}
// writing
out.println(int + "," + int); // multiple data
)
With socket.getOutputStream() you will get the same stream each time
You have to send the data in a struct , containing the score and health, or you have to send them separately in sequence (like first the health then the score or vicevesa)
This question already has answers here:
Java multiple file transfer over socket
(3 answers)
Closed 6 years ago.
I am doing a sample client-server socket project where the server sends a file to the client and the client saves it in a destination folder. It works well BUT it only works ONCE. I have to restart the server and reconnect the client in order to send another file.
What am I doing wrong?
Server:
public void doConnect() {
try {
InetAddress addr = InetAddress.getByName(currentIPaddress);
serverSocket = new ServerSocket(4445, 50, addr);
isServerStarted = true;
socket = serverSocket.accept();
inputStream = new ObjectInputStream(socket.getInputStream());
outputStream = new ObjectOutputStream(socket.getOutputStream());
String command = inputStream.readUTF();
this.statusBox.setText("Received message from Client: " + command);
} catch (IOException e) {
e.printStackTrace();
}
}
Method that I use to send the file from server
public void sendFile() {
fileEvent = new FileEvent();
String fileName = sourceFilePath.substring(sourceFilePath.lastIndexOf("/") + 1, sourceFilePath.length());
String path = sourceFilePath.substring(0, sourceFilePath.lastIndexOf("/") + 1);
fileEvent.setDestinationDirectory(destinationPath);
fileEvent.setFilename(fileName);
fileEvent.setSourceDirectory(sourceFilePath);
File file = new File(sourceFilePath);
if (file.isFile()) {
try {
DataInputStream diStream = new DataInputStream(new FileInputStream(file));
long len = (int) file.length();
byte[] fileBytes = new byte[(int) len];
int read = 0;
int numRead = 0;
while (read < fileBytes.length && (numRead = diStream.read(fileBytes, read, fileBytes.length - read)) >= 0) {
read = read + numRead;
}
fileEvent.setFileSize(len);
fileEvent.setFileData(fileBytes);
fileEvent.setStatus("Success");
} catch (Exception e) {
e.printStackTrace();
fileEvent.setStatus("Error");
}
} else {
System.out.println("path specified is not pointing to a file");
fileEvent.setStatus("Error");
}
//Now writing the FileEvent object to socket
try {
outputStream.writeUTF("newfile");
outputStream.flush();
outputStream.writeObject(fileEvent);
String result = inputStream.readUTF();
System.out.println("client says: " + result);
} catch (Exception e) {
e.printStackTrace();
}
}
Client
public void connect() {
int retryCount = 0;
while (!isConnected) {
if (retryCount < 5) {
try {
socket = new Socket(currentIPAddress, currentPort);
outputStream = new ObjectOutputStream(socket.getOutputStream());
inputStream = new ObjectInputStream(socket.getInputStream());
isConnected = true;
//connection success
String command = inputStream.readUTF();
if (command.equals("newfile")) {
this.clientCmdStatus.setText("Received a file from Server");
outputStream.writeUTF("Thanks Server! Client Received the file");
outputStream.flush();
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
new Thread(new DownloadingThread()).start();
}
} catch (IOException e) {
e.printStackTrace();
retryCount++;
}
} else {
//Timed out. Make sure Server is running & Retry
retryCount = 0;
break;
}
}
}
Code used for downloading file in client
public void downloadFile() {
try {
fileEvent = (FileEvent) inputStream.readObject();
if (fileEvent.getStatus().equalsIgnoreCase("Error")) {
System.out.println("Error occurred ..So exiting");
System.exit(0);
}
String outputFile = destinationPath + fileEvent.getFilename();
if (!new File(destinationPath).exists()) {
new File(destinationPath).mkdirs();
}
dstFile = new File(outputFile);
fileOutputStream = new FileOutputStream(dstFile);
fileOutputStream.write(fileEvent.getFileData());
fileOutputStream.flush();
fileOutputStream.close();
System.out.println("Output file : " + outputFile + " is successfully saved ");
serverResponsesBox.setText("File received from server: " + fileEvent.getFilename());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
In order to get the server accept another (and more) connections, you have to put it into a loop
while(someConditionIndicatingYourServerShouldRun) {
Socker socket = serverSocket.accept();
//respond to the client
}
I'd recommend using a thread pool and submit the processing to the thread pool, i.e. by using an ExecutorService. Further, you should close Resources such as stream when finished, the "try-with-resources" construct helps you with that. So your code might look like this
ServerSocket serverSocket = ...;
ExecutorService threadPool = Executors.newFixedThreadPool(10);
AtomicBoolean running = new AtomicBoolean(true);
while(running.get()) {
Socket socket = serverSocket.accept();
threadPool.submit(() -> {
try(ObjectInputStream is = new ObjectInputStream(socket.getInputStream());
OutputStream os = new ObjectOutputStream(socket.getOutputStream())) {
String command = is.readUTF();
if("shutdown".equals(command)) {
running.set(false);
} else {
this.statusBox.setText("Received message from Client: " + command);
}
} catch (IOException e) {
e.printStackTrace();
}
});
}
I coded a server application that constantly listens to data being sent to it. I took multi-threading into consideration by the way. I have the main thread, writer thread, and reader thread. When I launch the program, everything works perfectly. After about 15 minutes of up-time though, my CPU usage just randomly skyrockets. I believe it reaches about 40% just for the server application if I remember correctly. I think I'm doing something wrong with networking since this is my first time working with sockets.
This is what I use to read data:
public void run(){
Socket s = null;
InputStream in = null;
while (Main.running){
try {
s = network.getServerSocket().accept();
in = s.getInputStream();
} catch (IOException e){
e.printStackTrace();
}
if (in != null){
DataInputStream input = new DataInputStream(in);
try {
while (input.available() != -1) {
byte type = input.readByte();
PacketIn packet = Utils.getPacket(main, type);
packet.readData(input);
if (packet instanceof PacketInLogin) {
PacketInLogin login = (PacketInLogin) packet;
login.setSocket(s);
String server = login.getServer();
Socket socket = login.getSocket();
Main.log("Login request from server: '" + server + "'. Authenticating...");
boolean auth = login.authenticate();
Main.log("Authentication test for server: '" + server + "' = " + (auth ? "PASSED" : "FAILED"));
if (auth) {
main.getServers().put(server, new DataBridgeServer(main, server, socket));
}
main.getTransmitter().sendPacket(new PacketOutAuthResult(main, auth), socket);
} else if (packet instanceof PacketInDisconnect) {
PacketInDisconnect disconnect = (PacketInDisconnect) packet;
main.getServers().remove(disconnect.getServer().getName());
Main.log("'" + disconnect.getServer().getName() + "' has disconnected from network.");
}
}
} catch (IOException e){
if (!(e instanceof EOFException)){
e.printStackTrace();
}
} finally {
if (in != null){
try {
in.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
}
}
try {
if (s != null) s.close();
if (in != null) in.close();
} catch (IOException e){
e.printStackTrace();
}
}
This is what I use to write data (to the client. This code is still part of the server):
public void run(){
while (Main.running){
if (!QUEUED.isEmpty()){
PacketOut packet = (PacketOut) QUEUED.keySet().toArray()[0];
Socket server = QUEUED.get(packet);
DataOutputStream out = null;
try {
out = new DataOutputStream(server.getOutputStream());
packet.send(out);
} catch (IOException e){
e.printStackTrace();
} finally {
if (out != null){
try {
out.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
QUEUED.remove(packet);
}
}
}
I'm working on a little game that sends location data between a client an server to learn how Sockets work.
The server can send and receive data no problem, and the client can send data, but when the client tries to read in data from the server, the program hangs. (This part is commented out)
Server Code:
public void run() {
try {
serverSocket = new ServerSocket(10007);
} catch (IOException e) {
System.err.println("Could not listen on port: 10007.");
System.exit(1);
}
try {
System.out.println("Waiting for connection...");
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
System.out.println("Connection successful");
System.out.println("Waiting for input.....");
while (true) {
try {
in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
out = new PrintWriter(clientSocket.getOutputStream(), true);
if (in.readLine() != "0" && in.readLine() != null) {
setXY(in.readLine());
}
} catch (IOException e) {
e.printStackTrace();
}
out.println("X" + Graphics.charX);
out.println("Y" + Graphics.charY);
}
Client Code:
public void run() {
try {
System.out.println("Attemping to connect to host " + serverHostname + " on port " + serverPort + ".");
echoSocket = new Socket(serverHostname, serverPort);
} 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);
}
while (true) {
try {
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
out = new PrintWriter(echoSocket.getOutputStream(), true);
/*if (in.readLine() != "0" && in.readLine() != null) {
setXY(in.readLine());
}*/
} catch (IOException e2) {
e2.printStackTrace();
}
out.println("X" + Graphics.charX);
out.println("Y" + Graphics.charY);
}
}
Any help is much appreciated!
You need two threads to read/write blocking sockets at the same time (which is what you're trying to do). When you call in.readLine(), the current thread will block until it receives a line of data.
I made an app client in android device (with ethernet and wireless port) and server application in windows.
Data transfers via Socket programming between devices and when i test it in emulator in PC or run in Ethernet via cable it works correctly, but when i connect server and client with wireless connectivity (via an access point) data sent or received with a delay . this delay may be take over 60 seconds !
i don't know why this problem happend !
This is my sending routin in android :
Server_Port = mDbHelper.GetPortNumber();
//mDbHelper.close();
final String Concatinate_values = firstByte_KindType + Spliter + secoundByte_KindofMove +
Spliter + ValueOfMove + Spliter + valueOfsetting + Spliter + MaxOrMinValue;
//Sent Routin
////‌Connect To server
Thread thread = null;
thread = new Thread(new Runnable() {
#Override
public void run() {
DataOutputStream outputStream = null;
BufferedReader inputStream = null;
Socket socket;
socket = new Socket();
try {
socket.connect(new InetSocketAddress(Server_IP, Server_Port), 10);
}
catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
Thread.currentThread().interrupt();
}
////Make Read Line
try {
outputStream = new DataOutputStream(socket.getOutputStream());
inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
catch (IOException e1) {
//Finished Socket
ShutDown(socket);
}
if (outputStream == null) {
//
ShutDown(socket);
Thread.currentThread().interrupt();
return;
}
//Write Message
try {
String message = Concatinate_values + "\n";
outputStream.write(message.getBytes());
outputStream.flush();
ShutDown(socket);
Thread.currentThread().interrupt();
return;
}
catch (IOException e) {
e.printStackTrace();
Thread.currentThread().interrupt();
}
try {
if (socket != null) {
socket.close();
}
}
catch (IOException e) {
e.printStackTrace();
ShutDown(socket);
Thread.currentThread().interrupt();
return;
}
Thread.currentThread().interrupt();
}
});
thread.start();
My windows server code in c# :
class Program
{
static Socket socketForClient;
static NetworkStream networkStream;
static System.IO.StreamReader streamReader;
static System.IO.StreamWriter streamWriter;
static TcpListener tcpListener;
static int PORT;
static void Main(string[] args)
{
//Console.WriteLine("Enter Port : ");
//PORT = Convert.ToInt32(Console.ReadLine());
PORT = 12500;
Console.WriteLine("\n" + "Your Host Information Is : "+"\n" );
IPAddress[] localIPs = Dns.GetHostAddresses(Dns.GetHostName());
foreach (IPAddress ip in localIPs)
{
Console.WriteLine(ip.ToString());
}
while (true)
{
tcpListener = new TcpListener(PORT);
Console.WriteLine("\n >> Server started ... Waiting for Message");
tcpListener.Start();
try
{
socketForClient = tcpListener.AcceptSocket();
}
catch (System.Exception e1)
{
Console.WriteLine("LN: 40");
Console.WriteLine("Message: " + e1.Message);
Console.WriteLine("InnerException: " + e1.InnerException);
Console.WriteLine("Source: " + e1.Source);
Console.ReadLine();
}
if (socketForClient.Connected)
{
Console.WriteLine("Client connected");
try
{
networkStream = new NetworkStream(socketForClient);
}
catch (System.Exception e1)
{
Console.WriteLine("LN: 55");
Console.WriteLine("Message: " + e1.Message);
Console.WriteLine("InnerException: " + e1.InnerException);
Console.WriteLine("Source: " + e1.Source);
Console.ReadLine();
}
//System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkStream);
try
{
streamReader = new System.IO.StreamReader(networkStream);
streamWriter = new System.IO.StreamWriter(networkStream);
}
catch (System.Exception e1)
{
Console.WriteLine("LN: 71");
Console.WriteLine("Message: " + e1.Message);
Console.WriteLine("InnerException: " + e1.InnerException);
Console.WriteLine("Source: " + e1.Source);
Console.ReadLine();
}
string theString = "Sending";
// streamWriter.WriteLine(theString);
Console.WriteLine(theString);
//streamWriter.Flush();
long x = 0;
try
{
x++;
theString = streamReader.ReadLine();
if (theString.Trim() == "4-")
{
Console.WriteLine("Sending Report Data : 0-100-0-0");
streamWriter.WriteLine("0-70-0-0");
Console.WriteLine("pocket sent");
streamWriter.Flush();
}
Console.WriteLine(theString + x.ToString());
streamReader.Close();
networkStream.Close();
socketForClient.Close();
tcpListener.Stop();
}
catch (System.Exception e1)
{
streamReader.Close();
networkStream.Close();
socketForClient.Close();
Console.WriteLine("LN: 97");
Console.WriteLine("Message: " + e1.Message);
Console.WriteLine("InnerException: " + e1.InnerException);
Console.WriteLine("Source: " + e1.Source);
Console.ReadLine();
break;
//streamWriter.Close();
}
}
}
streamReader.Close();
networkStream.Close();
socketForClient.Close();
Console.WriteLine("Closed Socket");
Console.ReadLine();
}
}