I want to perform a two way communication between the client and the server and so far i have achieved one way communication.
My code in JAVA looks like,
ServerSide
public class server{
#SuppressWarnings("deprecation")
public static void main(String[] args)
{
try{
ServerSocket s=new ServerSocket(9998);
Socket ss=s.accept();
DataInputStream din=new DataInputStream(ss.getInputStream());
DataInputStream uip=new DataInputStream(System.in);
DataOutputStream dout=new DataOutputStream(ss.getOutputStream());
System.out.println("Enter message to send to client\n");
String stc=uip.readLine();
dout.writeBytes(""+stc);
din.close();
dout.close();
uip.close();
}
catch(Exception e)
{
System.out.println(e);
}`enter code here`
}
}
ClientSide
public class client{
public static void main(String[] args)
{
try{
Socket ss=new Socket("localhost",9998);
DataInputStream din=new DataInputStream(ss.getInputStream());
DataInputStream uip=new DataInputStream(System.in);
DataOutputStream dout=new DataOutputStream(ss.getOutputStream());
String msg=din.readLine();
System.out.println("Received msg is "+msg);
din.close();
dout.close();
uip.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
I tried to get input in the client side and tried to send in the same way to server. but thats not working. Where am i getting wrong? How Should i achieve a two way communication.
In the client side i got input from user and used .writeBytes(value); and performed readLine() in din in the server side as i have done above in one way communication. But that doesn't work. Where am i doing it wrong?
The best approach to create a double communication system is to create two threads one for writing messages and one to receive messages (both on client and server side).
The listening thread receive a message wake itself and do something. If a response is needed it create the response and add it to a queue.
The writing thread periodically check the queue of messages to be sent. If there are it sends them.
This is the best way for bidirectional client server communication.. "dout.shutdownOutput();" code this line after send function in client side.This is the function named as half socket closed it will helps to back and forth communication.
Related
Here is use case I need to implement in Java:
Server is listening for push messages from some clients
If client has some data to push into server, it opens TCP connection and sends all messages
When client sends last message (special message saying that this is the last one) server should close connection by starting TCP closing handshake
I have problem with last step because I don't know how to close connection from server site. My current code is bellow. How to initiate connection closing TCP handshake form server site? Thank you for any help.
public class Server{
public static void main(String[] args) throws Exception {
while (true) {
int port = AppConfig.getInstance().getPort();
try (ServerSocket socket = new ServerSocket(port)) {
Socket server = socket.accept();
InetAddress ipAddress = server.getInetAddress();
MessageHandler handler = new MessageHandler(ipAddress);
InputStream in = server.getInputStream();
// reads all bytes from input stream and process them by given handler
processStream(in, handler);
in.close();
server.close();
} catch (Exception e) {
LoggingUtils.logException(e);
}
}
}
private static void processStream(InputStream in, MessageHandler handler) throws Exception {
// implementation is omitted
}
}
You've done it. in.close() closes the input stream, the socket output stream, and the socket.
What you should really close is whatever output stream was attached to the socket, to ensure it gets flushed, and you should probably do that in the processStream() method, with a saver server .close() in a finally block in the calling method.
NB Your socket names are really the wrong way round. It is customary to use ServerSocket serverSocket, and Socket socket = serverSocket.accept().
I may be not totally sure about this one, but I would believe that socket.close() will send all the commands (FIN/FIN-ACK)
I have the code below which creates a socket UDP-style. I run and compile the code and it works just fine. If I then use "netcat -u " I am able to send messages from the client to the server but not the other way around. So what I want and what I have been trying to do is to read from stdin and printing it(all this running in a second thread). Making it a two-way communication. Anyone know what I need to fix? Thanks in advance.
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
public class NetcatUDP {
public static void main(String[] args) throws IOException {
int port = Integer.parseInt(args[0]);
byte[] buffer = new byte[65536];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
DatagramSocket socket = new DatagramSocket(port);
new Thread() {
#Override
public void run() {
// Read from stdin and send somehow?
}
}.start();
while (true) {
socket.receive(packet);
System.out.println(new String(packet.getData()).trim());
}
}
}
UDP is a connection-less protocol, which means you can send a message to anyone and receive a message from anyone with a single socket.
For the simple example you're using, you can actually use the same program for both endpoints. Besides reading in the local port number from the command line, read in the remote IP address and port as well. Then in your thread, you read from stdin using Console.readLine(), construct a DatagramPacket with the line read from the console, remote IP, and remote port, and send it with the existing socket you have.
I am making a messaging application that would connect two or more users on a local network and start messaging.It doesnot require an internet connection.
Now I don't know Where to make the socket and where serverSocket?
Who would be the client and who would be the server?
At the time the code that I've written is like this
....
static ServerSocket server;
static Socket client;
public static void main(String[] args) throws IOException {
try{
server=new ServerSocket(65474);
}
catch(IOException e){
System.out.println("Port not Free");
}
while(server.isClose()==false){
client=server.accept();
}
BufferedReader rdr=new BufferedReader(new InputStreamReader(client.getInputStream()));
From here ahead I will get the input from the client.
Is this code correct?Would client connect to the server correctly?
You are infinitely accepting clients BUT you will never get to read their data.
You should put it like that:
while(!server.isClosed() {
client=server.accept();
BufferedReader rdr=new BufferedReader(new InputStreamReader(client.getInputStream()));
}
You can remove the ==false and just negate the boolean youre getting.
It will be set to true if it returns false and false if it returns true.
Dont forget to read the data and to display it on the screen like:
String receivedText = rdr.readLine();
System.out.println(receivedText);
I am trying to write a program that acts as a proxy server.
Proxy server basically listens to a given port (7575) and sends the request to the server.
As of now, I did not implement caching the response.
The code looks like
ServerSocket socket = new ServerSocket(7575);
Socket clientSocket = socket.accept();
clientRequestHandler(clientSocket);
I changed the above code as below: //calling the same clientRequestHandler method from inside another method.
Socket clientSocket = socket.accept();
Thread serverThread = new Thread(new ConnectionHandler(client));
serverThread.start();
class ConnectionHandler implements Runnable {
Socket clientSocket = null;
ConnectionHandler(Socket client){
this.clientSocket = client;
}
#Override
public void run () {
try {
PrxyServer.clientRequestHandler(clientSocket);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Using the code, I am able to open a webpage like google. However, if I open another web page even I completely receive the first response, I get connection reset by peer expection.
1. How can I handle this issue
Can I use threading to handle different requests. Can someone give a reference where I look for example code that implements threading.
I have searched everywhere to find an answer for this question:
I have a TCP client on my android application that sends an message to the server which is written in Visual Basic .NET Framework 4.
Now i want to send an message from my server to the phone over 3g, it works on wifi and 3g..
private class startserver extends Thread
{
public void server() throws Exception
{
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(8765);
while(true)
{
Socket connectionSocket = welcomeSocket.accept();
BufferedReader inFromClient =
new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
clientSentence = inFromClient.readLine();
System.out.println(clientSentence.substring(1));
msgshower = clientSentence.substring(1);
MainActivity.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(MainActivity.this, "Received: " + msgshower , Toast.LENGTH_LONG).show();
}
});
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeBytes(capitalizedSentence);
}
}
#Override
public void run() {
try {
server();
} catch (Exception e) {
e.printStackTrace();
}
}
I start it in the OnCreate method
Now i send a message with (VB.NET)
Private Sub sends(ByVal message As String)
Dim tcp As New TcpClient
tcp.Connect(connectedIP, 8765)
Dim bw As New IO.BinaryWriter(tcp.GetStream)
bw.Write(message)
bw.Close()
tcp.Close()
End Sub
On wifi it will arrive, on 3g it wont... any idea's how to do this?
How do other applications archive this?
I think you're having problem with the ip address asigned by your mobile phone operator. The fact that works on wifi, but not on 3G, I think that is because your mobile(when connected through 3G) doesn't have a public IP address.
When you use SocketServer in your mobile, you're opening a port a waiting for others to connect to it. If your IP address is not reachable from internet, it won't happen (it's like having a computer behind a firewall.)
Could you try to implement the server in the VB machine, assuming that it has a public reachable address? This way, the phone wouldn't act as a server, it wouldn't be necessary to have a reachable address, as long as the VB machine has one. Then, you should use Socket class to bind to the server ip and port.
Totally confused by your code list above..
If you want to host a server in VB.NET, you should not use TcpClient class but TcpListener and if you need a better performance, use Socket class directly.
At the Android client side, you should new Socket(server,servPort), when you want to send message, write the outputStream, and read the inputStream to receive message.