Java UDP p2p chatprogram. - java

im making a P2P chat program. for this i use UDP datagrams. but im having some problems.
sometimes the program works without any problems. but most of the times only 1 of the 2 people recieve the message or sometimes neither of the 2 people get a message. im thinking about going to TCP but i want to keep it P2P so no central server.
my code:
package herexChatProg;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import javax.swing.JOptionPane;
import login.MainScreen;
public class MessageSender extends Thread {
private int Port;
private String recIP;
private final static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
private MainScreen Screen;
private DatagramSocket ds = null;
private DatagramPacket dp = null;
public MessageSender(MainScreen m, String ip, int port) throws Exception {
recIP = ip;
Port = port;
Screen = m;
System.out.println("chat program: IP address: " + recIP + " port " + Port);
start();
}
public void run() {
try {
// open DatagramSocket to receive
ds = new DatagramSocket(Port);
// loop forever reading datagrams from the DatagramSocket
while (true) {
byte[] buffer = new byte[65000]; // max char length
dp = new DatagramPacket(buffer, buffer.length);
ds.receive(dp);
String s = new String(dp.getData(), 0, dp.getLength());
Screen.writeText(s);
// System.out.println("UDP datagram length " + s.length() + "
// from IP " + dp.getAddress() + " received: " + s);
}
} catch (SocketException se) {
System.err.println("chat error (Socket Closed = good): " + Se.getMessage());
JOptionPane.showMessageDialog(null, "Please check your connection or try to log on again");
} catch (IOException se) {
System.err.println("chat error: " + se.getMessage());
}
}
public void Stop() {
if (ds != null) {
ds.close();
ds = null;
}
}
public boolean sendMessage(String message) throws IOException {
try {
System.out.println("Sending to " + recIP + " socket " + Port + " data: " + message);
byte[] data = message.getBytes();
DatagramSocket theSocket = new DatagramSocket();
DatagramPacket theOutput = new DatagramPacket(data, data.length, InetAddress.getByName(recIP), Port);
theSocket.send(theOutput);
Screen.writeText(message);
return true;
} catch (IOException e) {
return false;
}
}
}
if any of you spot the problem or can help me that would be great
thanks DenTilloZie

if any of you spot the problem or can help me that would be great
The "problem" of not all messages reaching their destination is normal, it's because UDP is unreliable. It isn't due to your code (well due to the fact you're using UDP instead of TCP).
If you want to be sure that each message arrives at its destination you have 2 possibilities. You could use TCP instead of UDP as TCP guarantees each message arrive (and guarantees even more). If you really want to continue with UDP you will have to send an acknowledge (to the original sender of the message) when receiving a message. When a sender receives the acknowledge he can be sure the message arrived at its destination. However there are a lot of extra problems you should fix if you use UDP (message order, ...). So i would just recommend to use TCP instead of reinventing the wheel.
im thinking about going to TCP but i want to keep it P2P so no central server.
This will be hard to achieve. There are different possibilities for implementing a Peer-to-peer system :
With a central coordinater
By flooding
By distributed hash tables
The first approach is the simplest but is not possible as you explicitly want no central server. But the other approaches are considerably more difficult.

Related

Java Publisher Sever chat program

I am trying to create a chat application which has one publisher, one server and multiple subscribers. The publisher(Sending to port 8000) sends a message to the server(listening on port 8000 and 5000) and which forwards it further to the subscriber(listening on port 5000).
Now so far I can create multiple publishers and the communication between server and publisher is working, however, I am not able to send it to the subscriber the message sent by the publisher
Server Side Code
package serverclient;
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Server extends Thread{
private Socket socket;
private int clientNumber;
public Server(Socket socket, int clientNumber){
this.socket = socket;
this.clientNumber = clientNumber;
if(socket.getLocalPort() == 5000)System.out.print("\nSubscriber "+ clientNumber +" is connected to the server");
if(socket.getLocalPort() == 8000)System.out.print("\nPublisher "+ clientNumber +" is connected to the server");
}
#Override
public void run(){
try {
BufferedReader dStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
while(true){
synchronized(this){
String clMessage = dStream.readLine();
System.out.println("\n"+clMessage);
// if(socket.getLocalPort() == 5000){
out.println("Hey the server is sending the message to subscriber");
// }
//out.println("Hey the publisher has sent the message : " + clMessage);
}
}
} catch (IOException ex) {
System.out.print("\nError has been handled 1\n");
}finally{
try {
socket.close();
} catch (IOException ex) {
System.out.print("\nError has been handled 2\n");
}
}
}
public static void main(String [] args) throws IOException{
int subNumber = 0;
int pubNumber = 0;
ServerSocket servSockpub = new ServerSocket(8000);
ServerSocket servSocksub = new ServerSocket(5000);
try {
while (true) {
Server servpub = new Server(servSockpub.accept(),++pubNumber);
servpub.start();
System.out.print("\nThe server is running on listen port "+ servSockpub.getLocalPort());
Server servsub = new Server(servSocksub.accept(),++subNumber);
servsub.start();
System.out.print("\nThe server is running on listen port "+ servSocksub.getLocalPort());
}
} finally {
servSockpub.close();
servSocksub.close();
}
}
}
publisher code
package serverclient;
import java.net.*;
import java.io.*;
public class Publisher {
public static void main (String [] args) throws IOException{
Socket sock = new Socket("127.0.0.1",8000);
// reading from keyboard (keyRead object)
BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
// sending to client (pwrite object)
OutputStream ostream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream, true);
InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
System.out.println("Start the chitchat, type and press Enter key");
String receiveMessage,sendMessage;
while(true)
{
sendMessage = keyRead.readLine(); // keyboard reading
pwrite.println(sendMessage); // sending to server
pwrite.flush(); // flush the data
if((receiveMessage = receiveRead.readLine()) != null) //receive from server
{
System.out.println(receiveMessage); // displaying at DOS prompt
}
else{
System.out.print("Null");
}
}
}
}
subscriber
package serverclient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class Subscriber {
public static void main (String [] args) throws IOException{
Socket sock = new Socket("127.0.0.1",5000);
// receiving from server ( receiveRead object)
InputStream istream = sock.getInputStream();
BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));
System.out.println("Recive side");
String receiveMessage, sendMessage;
while(true)
{
System.out.print("Hey man " + receiveRead.readLine() + "\n");
if((receiveMessage = receiveRead.readLine()) != null) //receive from server
{
System.out.println(receiveMessage); // displaying at DOS prompt
}
else{
System.out.print("Null");
}
}
}
}
Any help is appreciated. I just want to figure out why subscriber is not reciveing message
There are many possibilities to handle realm time communication issues. I myself prefer the use of Events / EventListeners.
Currently in your program there is no communication between the Server as such and the threads which handle the subscriber connection.
Also on a side node: even with a proper communication between publisher connection threads and subscriber connection threads it won't work now since you are using the same Server class. This does not only violate the Single-Responsibility-Principle but will also prevent the server from ever sending a message to the Subscriber.
Let's say you have establish a connection and your server class is now connected with the subscriber. What will happen?
The subscriber will loop until there is a message on the input stream of his socket. Good that is exactly what we want. But what does the server do? The truth is exactly the same. The first few statements in the try block of your Server's run method are to create a BufferedReader and read from it until a message receives. And now we have a socket on each site which will infinitly wait for some kind of message to arrive (which will obviously never happen since both are waiting for something).
To prevent this you should check if there is anything to read on the stream first:
while ( true )
{
if ( socket.getInputStream().available() != 0 )
{
// reading logic goes here....
synchronized ( this )
{
String clMessage = dStream.readLine();
System.out.println( "\n" + clMessage );
out.println( "Hey the server is sending the message to subscriber" );
}
}
// what shall be done when not reading.
}
Now the second part. If you want to communicate between threads you need to implement some logic to do so. As stated above I love the concept of Listeners so i will show an example where I make use of them:
MessageReceivedListener.java
import java.util.EventListener;
public interface MessageReceivedListener
extends EventListener
{
public void onMessageReceived( String message );
}
Note: The interface does not have to extend EventListener since EventListener
is just a tagging interface. I myself still prefer to have this as a reminder for what purpose the interface is there.
Server.java (excerpt)
// New constructor since we will pass a Listener now. Also new local variable for it.
public Server( Socket socket, int clientNumber, MessageReceivedListener mrl )
{
this.socket = socket;
this.clientNumber = clientNumber;
this.mrl = mrl;
if ( socket.getLocalPort() == 5000 )
System.out.print( "\nSubscriber " + clientNumber + " is connected to the server" );
if ( socket.getLocalPort() == 8000 )
System.out.print( "\nPublisher " + clientNumber + " is connected to the server" );
}
The new constructor provides a way to pass the MessageReceivedListener to the Server object. Alternatively you can alsocreate a setter for it.
synchronized ( this )
{
String clMessage = dStream.readLine();
System.out.println( "\n" + clMessage );
out.println( "Hey the server is sending the message to subscriber" );
mrl.onMessageReceived( clMessage );
}
This is where the magic happens. After whe receive the message we just pass it to the onMessageReceived(String message) method of the listener. But what does it do exactly? This is what we define when creatinga Server object.
Here are two examples, one with anonymous classes (Java 7 and before) and on with lambdas (Java 8 and later).
Example Java 7 and earlier
Server servpub = new Server( servSockpub.accept(), ++pubNumber,
new MessageReceivedListener()
{
#Override
public void onMessageReceived( String message )
{
// call nother local method
// this method would need to be a static method of Server
// because it's in the scope of your server class
sendMessageToSubscribers(message);
}
} );
Here we pass an anonymous class as our MessageReceivedListener object and define it's behaviour (in this case just calling another method which will handle the rest.
Now since our MessageReceivedListener interface does only contain one method we can also see it as a functional interface and therefore use lambdas to shorten the code and improve readability.
Example with Lambda (Java 8 and later)
Server servpub = new Server( servSockpub.accept(), ++pubNumber, Server::sendMessageToSubscribers);
In this specific case we only have one argument which we want to pass to a method and therefore can use a method reference.
How to actually implement the method sendMessageToSubs(String message) is up to you. But you need to keep track of how many Threads with subscriber connections have been created and how you want to reference them.

Get full URL path from browser with using ServerSocket and Socket classes

I'm trying write my individual HTTP Server and I need a help .
What is the method of ServerSocket or Socket class can to invoke on the URL and brining it into a code.
For example, if I write following link <b>http://localhost:8080/coupon/add?name=coupon name</b> in browser, I would be want to get this link into my code.
Maybe who know how can I do this?
my simple code:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class HTTPServer {
public static void main(String[] args) {
new HTTPServer().startServer();
}
public void startServer() {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
System.out.println("Server is started");
while (true) {
Socket socket = serverSocket.accept();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Thanks
All your code does right now is set up a TCP server.
HTTP is a Layer 7 protocol.
Once you accept the connection from the client, HTTP can be used for communication over that TCP socket.
You'd have to parse the HTTP request that the client sends, and from that, you'd know the URL.
In your case, you said:
I write following link http://localhost:8080/coupon/add?name=coupon name in browser
Your browser will send an HTTP request like the following example:
GET /coupon/add?name=coupon+name HTTP/1.0
Host: localhost:8080
In reality, there will be more HTTP headers there, as well as a trailing \r\n, but for our sake, let's keep it simple.
Note that special characters like space are URL-encoded, however space is also encoded as + in the query string - it could be either + or %20 depending on the client.
Hopefully it's reasonably clear to you from this explanation how you get the URL from this HTTP request.
The only missing part from the actual full link is the http:// part. The distinction between HTTP and HTTPS is not part of the HTTP protocol - it's above the socket layer but below the HTTP protocol layer. If you had SSL sockets, you'd know that on the server side, and determine based on whether it was an SSL socket or a "plain" socket, whether it was http or https.
Hope that helps.
I improved for testing the startServer method for getting information.
I'm trying to include the data that comes from URL from any browsers to URI or URL class of JAVA.
This impossible ? Maybe who know how can I do this ?
public void startServer() {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
System.out.println("Server is started");
while (true) {
Socket socket = serverSocket.accept();
System.out.println("SERVER SOCKET TESTS:");
System.out.println("getChannel: " + serverSocket.getChannel());
System.out.println("getInetAddress: " + serverSocket.getInetAddress());
System.out.println("getLocalPort: " + serverSocket.getLocalPort());
System.out.println("getLocalSocketAddress: " + serverSocket.getLocalSocketAddress());
System.out.println();
System.out.println("CLIENT SOCKET TESTS:");
System.out.println("getChannel: " + socket.getChannel());
System.out.println("getLocalAddress: " + socket.getLocalAddress());
System.out.println("getLocalPort: " + socket.getLocalPort());
System.out.println("getLocalSocketAddress: " + socket.getLocalSocketAddress());
System.out.println("getRemoteSocketAddress: " + socket.getRemoteSocketAddress());
System.out.println("getInetAddress: " + socket.getInetAddress());
System.out.println("getInputStream: " + socket.getInputStream());
System.out.println("getOutputStream: " + socket.getOutputStream());
System.out.println();
System.out.println("URI - GET INFORMATION:");
URI uri = new URI("httpscheme://world.hello.com/thismy?parameter=value");
System.out.println(uri.getHost());
System.out.println(uri.getPath());
System.out.println(uri.getQuery());
System.out.println(uri.getScheme());
}
} catch (Exception e) {
System.out.println("error");
}
}
little test:
when I run code and after that open the browser and I write in my browser, for example: http://localhost:8080 I get information, but I don't understand following:
why the serverSocket object in getInetAddress method (serverSocket.getInetAddress) have an IP4 and it 0.0.0.0 (why not a standard local ip that defined on my computer) and the socket object of getInetAddress method (socket.getInetAddress) have an IP6 and it 0:0:0:0:0:0:0:1 . How can I get a standard host name localhost how to get the URI class (with chunks of data of link)?
The port is gated nice: 8080.
The problem for getting URL path , solved.
package pk6HttpServer;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Created by Morris on 08/10/16.
*/
public class HTTPServer {
private static String headerData;
public static void main(String[] args) {
new HTTPServer().startServer();
}
public void startServer() {
try (ServerSocket serverSocket = new ServerSocket(8080)) {
boolean isClosed = false;
System.out.println("Server is started");
while (true) {
Socket socket = serverSocket.accept();
try {
try (InputStream raw = socket.getInputStream()) { // ARM
System.out.println("=================BEFORE STARTING READING HEADER =======================");
System.out.println("Collecting data to string array...");
headerData = getHeaderToArray(raw);
//
System.out.println("+++++++++++++++++ AFTER ENDING READING HEADER +++++++++++++++++++++++");
System.out.println("Hello World");
}
} catch (MalformedURLException ex) {
System.err.println(socket.getLocalAddress() + " is not a parseable URL");
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
}
} catch (Exception ex) {
System.out.println("error# " + ex.getMessage());
}
}
public static String getHeaderToArray(InputStream inputStream) {
String headerTempData = "";
// chain the InputStream to a Reader
Reader reader = new InputStreamReader(inputStream);
try {
int c;
while ((c = reader.read()) != -1) {
System.out.print((char) c);
headerTempData += (char) c;
if (headerTempData.contains("\r\n\r\n"))
break;
}
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
headerData = headerTempData;
return headerTempData;
}
}

Messaging between Android and Desktop

I'm trying to make an Android app that's able to send a message to a computer and receive one from it. It's pretty basic. The thing is, I have accomplished this through multicasting, although not exactly. My app is able to receive messages from the computer (which uses a java application I made to receive and send the messages). But, when I try to send a message from the device to the computer, the message doesn't arrive to the computer. I mean, to the application.
Both the desktop app and the Android app use the same Client - Server classes. This is what gets me so confused. Because, as I am using the same classes, why does it work one way but not the other? I just don't no.
The desktop app runs on windows.
Also, when the Android app receives a message, it receives it the following way: "Message 1���������������������������..." when the message should be received: "Message 1". I don't know if this could be relevant.
The code is the following:
Server Class:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class MulticastSocketServer implements Runnable{
final static String INET_ADDR = "224.0.0.3";
final static int PORT = 8888;
static String msg;
public MulticastSocketServer(String message) throws UnknownHostException, InterruptedException {
msg = message;
Thread thread = new Thread(this);
thread.start();
}
#Override
public void run() {
// TODO Auto-generated method stub
// Get the address that we are going to connect to.
InetAddress addr = null;
try {
addr = InetAddress.getByName(INET_ADDR);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Open a new DatagramSocket, which will be used to send the data.
try (DatagramSocket serverSocket = new DatagramSocket()) {
msg += "\\0";
for (int i = 0; i < 10; i++) {
// Create a packet that will contain the data
// (in the form of bytes) and send it.
DatagramPacket msgPacket = new DatagramPacket(msg.getBytes(),
msg.getBytes().length, addr, PORT);
serverSocket.send(msgPacket);
System.out.println("Server sent packet with msg: " + msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
serverSocket.disconnect();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Client Class:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import java.util.Timer;
import java.util.TimerTask;
public class MulticastSocketClient implements Runnable {
final static String INET_ADDR = "224.0.0.3";
final static int PORT = 8888;
Connection360 conn;
public MulticastSocketClient (Connection360 connection) throws UnknownHostException {
conn = connection;
Thread thread = new Thread(this);
thread.start();
}
#Override
public void run() {
try{
// Get the address that we are going to connect to.
InetAddress address = InetAddress.getByName(INET_ADDR);
// Create a buffer of bytes, which will be used to store
// the incoming bytes containing the information from the server.
// Since the message is small here, 256 bytes should be enough.
byte[] buf = new byte[256];
// Create a new Multicast socket (that will allow other sockets/programs
// to join it as well.
try (final MulticastSocket clientSocket = new MulticastSocket(PORT)){
//Joint the Multicast group.
clientSocket.joinGroup(address);
System.out.println("Connected");
//while (true) {
// Receive the information and print it.
DatagramPacket msgPacket = new DatagramPacket(buf, buf.length);
Timer timer = new Timer("tmr");
timer.schedule(new TimerTask() {
#Override
public void run() {
clientSocket.disconnect();
}
},10000);
clientSocket.receive(msgPacket);
String msg = new String(buf, 0, buf.length);
System.out.println("Socket 1 received msg: " + msg.substring(0, msg.indexOf("\\0")));
conn.MessageReceived(msg.substring(0, msg.indexOf("\\0")));
clientSocket.disconnect();
//}
} catch (IOException ex) {
ex.printStackTrace();
}
}catch (UnknownHostException ex){
}
}
}
This classes are the ones I made for the desktop app. The classes I made for the Android app are the same, but I had to change the System.out.println() to Log.v(). As for the rest, it's exactly the same.
So, if you happen to know what could be happening, I would really appreciate your assistance with the topic.
Thank you!
When you read the incoming packet, you don't use its size but the size of the buffer instead:
String msg = new String(buf, 0, buf.length);
// should be:
String msg = new String(buf, 0, msgPacket.getLength());
// or even better:
String msg = new String(msgPacket.getData());
If the incoming packet is shorter, the rest of the buffer contains random data which is what you got. Java strings are not NUL-terminated so msg.indexOf("\\0") does not work.

Copy a Different Program's Local Server (Java)

First off, networking is not my strongest subject. So sorry if this question is ridiculous, or if I'm missing some major information. I'd be happy to provide any needed.
I am trying spoof a server program. The program I am trying to pretend to be basically creates a local server, then allows client versions of the same program to connect (provided they are on the same computer).
Using netstat -a -b -n I was able to figure out that the server was binding itself to 0.0.0.0:53640. The other information given was:
Proto: UDP
Local Address: 0.0.0.0:56426
Foreign Address: * : * (Without spaces, stackoverflow doesn't seem to like this when it doesn't have them)
State: (Was blank)
The closest I was able to come was
Proto: TCP
Local Address: 0.0.0.0:56426
Foreign Address: 0.0.0.0:0
State: LISTENING
The code that I am using is:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
public class Main2
{
public static void main(String args[])
{
String ip = "0.0.0.0";
int port = 53640;
try
{
InetAddress address = InetAddress.getByName(ip);
ServerSocket server = new ServerSocket(port, 5, address);
System.out.println("Waiting for connection...");
Socket socket = server.accept();
System.out.println("Got connection!");
doSocket(socket);
server.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static void doSocket(Socket socket)
{
try
{
System.out.println("Connection from: " + socket.getInetAddress());
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream());
int b;
char c;
while ((b = in.read()) != -1)
{
c = (char) b;
System.out.print(c);
}
in.close();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
ServerSocket.accept seems to never stop yielding, as "Got connection!" is never printed to the output.
All help is very welcome. Thanks in advance! And sorry if I've done something horribly wrong with this post, its my first one.
UDP is connection-less, and 'ServerSocket' is connection-oriented and TCP-only. Have a look at the Oracle docs on datagrams (UDP).
UDP ports and TCP ports are in different namespaces; you can't get mixups from one to the other.

improving speed of comunication in java sockets

I am trying to improve the speed at which the sockets transfer information but i am unsure how to do so. the pourpose of the code is to transfer a number, the date, and a short xml which is being sent in the form of a string.
this is the server code
import java.net.*;
import java.io.*;
public class SSocket extends Thread
{
private ServerSocket serverSocket;
public SSocket(int port) throws IOException
{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(100000);
}
public void run()
{
System.out.println("Waiting for client on port " + serverSocket.getLocalPort() + "...");
while(true)
{
try
{
Socket server = serverSocket.accept();
DataInputStream in = new DataInputStream(server.getInputStream());
int cor=in.readInt();
int i=0;
String transaccion = in.readUTF();
String fecha = in.readUTF();
System.out.println(cor);
System.out.println(transaccion);
System.out.println(fecha);
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
if(transaccion!=null && fecha != null && cor>0){
out.writeInt(cor);
}
else {
out.writeInt(-1);
}
if (i==100){
out.flush();
i=0;
}
i++;
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;
}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
int port = 1337;
try
{
Thread t = new SSocket(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
the code for the client is
import java.net.*;
import java.io.*;
public class ClientSocket
{
public static void send(int correl, String transaccion, String fecha)
{
String serverName = "localhost";
int port = 1337;
try
{
Socket client = new Socket(serverName, port);
int i=0;
OutputStream outToServer = client.getOutputStream();
DataOutputStream out =
new DataOutputStream(outToServer);
out.writeInt(correl);
out.writeUTF(transaccion);
out.writeUTF(fecha);
InputStream inFromServer = client.getInputStream();
DataInputStream in =
new DataInputStream(inFromServer);
int corin=in.readInt();
if(corin>0){
Envio.updater(corin);
}
else {
}
if (i==100){
out.flush();
i=0;
}
i++;
client.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
i have done some reading on the mater and it seems that posible solutions are to use either a buffer or swich to a datagram. however my experience on working with sockets is rather limited and i am unsure which would be best to use for this situation or if there is another option i havent yet considered. this code will be moving many transactions and i wish to do it in as short time as posible.
thanks in advance
ps. sorry for my bad english it is not my first language
Datagrams imply UDP, which is an unreliable delivery protocol so you're not guaranteed to get all content. That's probably not what you want; I'd stay with plain Sockets (which use TCP, which has reliable delivery).
Will the same client be calling send() repeatedly and connecting to the same server each time? That is, will there be many messages going across a single connection, or will each message be to a different server, with only a single message (or only a few) going to each of the many servers? If there's just one server that a client is going to connect to and if a given client is going to send lots of messages, you should keep the Socket open between send() calls; setting up and tearing down Sockets is expensive, so you're paying a high price for making a new connection each time.
Also, your server appears to only be able to handle a single connection at a time: you accept a connection, read from it, and then close it and accept a new one. So to make this work for more than one client, you'll need to separate the logic for accepting connections onto a different thread from the logic that reads data. If you'll only have a few clients at a time, you can just start a new thread to read from each socket as you create it for a new client; if you'll have lots of clients (thousands), you'll probably need to look at NIO for its ability to service multiple sockets from a single thread. But I suspect you're a long way from having that problem, if you ever do, so I'd just spawn a new thread for each socket.

Categories