what's wrong with my code?
sorry about my bad English
package sockettest;
import java.io.*;
import java.net.*;
class sevr implements Runnable{
public void run() {
ServerSocket sSkt = null;
Socket skt = null;
BufferedReader br = null;
BufferedWriter bw = null;
try{
System.out.println("Server: is about to create socket");
sSkt = new ServerSocket(6666);
System.out.println("Server: socket created");
}
catch(IOException e){
System.out.println("Server: socket creation failure");
}
try{
System.out.println("Server: is listening");
skt = sSkt.accept();
System.out.println("Server: Connection Established");
}
catch(IOException e){
System.out.println("Server: listening failed");
}
try{
System.out.println("Server: creating streams");
br = new BufferedReader(new InputStreamReader(skt.getInputStream()));
bw = new BufferedWriter(new OutputStreamWriter(skt.getOutputStream()));
System.out.println("Server: stream done");
}
catch(IOException e){
System.out.println("Server: stream failed");
}
System.out.println("Server: reading the request");
try{
String line = null;
while((line =br.readLine()) != null){
System.out.println("Server: client said-> "+ line);
}
}
catch(IOException e){
System.out.println("Server: reading failed");
}
System.out.println("Server: reading fished");
System.out.println("Server: responding");
try{
bw.write("Hi! I am server!");
}
catch(IOException e){
System.out.println("Server: responding failed");
}
System.out.println("Server: responding finished");
System.out.println("Server: is finishing");
try {
br.close();
bw.close();
skt.close();
sSkt.close();
} catch (IOException e) {
System.out.println("Server: finishing failed");
}
System.out.println("Server: done");
}
}
class clnt implements Runnable{
public void run() {
Socket skt = null;
BufferedReader br = null;
BufferedWriter bw = null;
try{
System.out.println("Client: about to create socket");
skt = new Socket(InetAddress.getLocalHost(),6666);
System.out.println("Client: socket created");
}
catch(IOException e){
System.out.println("Client: socket creation failure");
}
try{
System.out.println("Client: creating streams");
br = new BufferedReader(new InputStreamReader(skt.getInputStream()));
bw = new BufferedWriter(new OutputStreamWriter(skt.getOutputStream()));
System.out.println("Client: stream done");
}
catch(IOException e){
System.out.println("Client: stream failed");
}
System.out.println("Client: requesting");
try{
bw.write("Hi! I am Client!");
}
catch(IOException e){
System.out.println("Client: requesting failed");
}
System.out.println("Client: requesting finished");
System.out.println("Client: reading the respond");
try{
String line = null;
while((line =br.readLine()) != null){
System.out.println("Client: server said-> "+ line);
}
}
catch(IOException e){
System.out.println("Client: reading failed");
}
System.out.println("Client: reading fished");
System.out.println("Clientrver: is finishing");
try {
br.close();
bw.close();
skt.close();
} catch (IOException e) {
System.out.println("Client: finishing failed");
}
System.out.println("Client: done");
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Main started");
Thread sThread = new Thread(new sevr());
Thread cThread = new Thread(new clnt());
sThread.start();
cThread.start();
try {
sThread.join();
cThread.join();
} catch (InterruptedException ex) {
System.out.println("joining failed");
}
System.out.println("Main done");
}
}
output:
Main started
Server: is about to create socket
Client: about to create socket
Client: socket created
Client: creating streams
Server: socket created
Server: is listening
Server: Connection Established
Server: creating streams
Server: stream done
Server: reading the request
Client: stream done
Client: requesting
Client: requesting finished
Client: reading the respond
and it waits here forever!
The program is using a BufferedWriter but this is not flushed (it will sit in the buffer until it is flushed, the buffer fills or closed) and there is no newline sent (the readLine will wait until you send a newline)
try
bw.write("I am the Client!!\n");
bw.flush();
Both threads hang on while((line =br.readLine()) != null)
now it works
package sockettest;
import java.io.*;
import java.net.*;
class sevr implements Runnable{
public void run() {
ServerSocket sSkt = null;
Socket skt = null;
BufferedReader br = null;
BufferedWriter bw = null;
try{
System.out.println("Server: is about to create socket");
sSkt = new ServerSocket(6666);
System.out.println("Server: socket created");
}
catch(IOException e){
System.out.println("Server: socket creation failure");
}
try{
System.out.println("Server: is listening");
skt = sSkt.accept();
System.out.println("Server: Connection Established");
}
catch(IOException e){
System.out.println("Server: listening failed");
}
try{
System.out.println("Server: creating streams");
br = new BufferedReader(new InputStreamReader(skt.getInputStream()));
bw = new BufferedWriter(new OutputStreamWriter(skt.getOutputStream()));
System.out.println("Server: stream done");
}
catch(IOException e){
System.out.println("Server: stream failed");
}
System.out.println("Server: reading the request");
try{
String line = null;
line = br.readLine();
System.out.println("Server: client said-> "+ line);
}
catch(IOException e){
System.out.println("Server: reading failed");
}
System.out.println("Server: reading fished");
System.out.println("Server: responding");
try{
bw.write("Hi! I am server!\n");
bw.flush();
}
catch(IOException e){
System.out.println("Server: responding failed");
}
System.out.println("Server: responding finished");
System.out.println("Server: is finishing");
try {
br.close();
bw.close();
skt.close();
sSkt.close();
} catch (IOException e) {
System.out.println("Server: finishing failed");
}
System.out.println("Server: done");
}
}
class clnt implements Runnable{
public void run() {
Socket skt = null;
BufferedReader br = null;
BufferedWriter bw = null;
try{
System.out.println("Client: about to create socket");
skt = new Socket(InetAddress.getLocalHost(),6666);
System.out.println("Client: socket created");
}
catch(IOException e){
System.out.println("Client: socket creation failure");
}
try{
System.out.println("Client: creating streams");
br = new BufferedReader(new InputStreamReader(skt.getInputStream()));
bw = new BufferedWriter(new OutputStreamWriter(skt.getOutputStream()));
System.out.println("Client: stream done");
}
catch(IOException e){
System.out.println("Client: stream failed");
}
System.out.println("Client: requesting");
try{
bw.write("Hi! I am Client!\n");
bw.flush();
}
catch(IOException e){
System.out.println("Client: requesting failed");
}
System.out.println("Client: requesting finished");
System.out.println("Client: reading the respond");
try{
String line = null;
line =br.readLine();
System.out.println("Client: server said-> "+ line);
}
catch(IOException e){
System.out.println("Client: reading failed");
}
System.out.println("Client: reading fished");
System.out.println("Client: is finishing");
try {
br.close();
bw.close();
skt.close();
} catch (IOException e) {
System.out.println("Client: finishing failed");
}
System.out.println("Client: done");
}
}
public class Main {
public static void main(String[] args) {
System.out.println("Main started");
Thread sThread = new Thread(new sevr());
Thread cThread = new Thread(new clnt());
sThread.start();
cThread.start();
try {
sThread.join();
cThread.join();
} catch (InterruptedException ex) {
System.out.println("joining failed");
}
System.out.println("Main done");
}
}
output:
Main started
Server: is about to create socket
Client: about to create socket
Client: socket created
Client: creating streams
Server: socket created
Server: is listening
Server: Connection Established
Server: creating streams
Client: stream done
Server: stream done
Server: reading the request
Client: requesting
Client: requesting finished
Client: reading the respond
Server: client said-> Hi! I am Client!
Server: reading fished
Server: responding
Server: responding finished
Server: is finishing
Client: server said-> Hi! I am server!
Client: reading fished
Client: is finishing
Client: done
Server: done
Main done
Related
I am opening an SSLSocket on the client side to connect to the server.
But trying to get the socket.getOutputStream() blocks the code, without outputting any errors.
I am flushing both streams, but it still doesn't work.
Server:
SSLSocket socket = (SSLSocket) serverSocket.accept();
socket.setUseClientMode(false);
try{
socket.setSoTimeout(0);
socket.setKeepAlive(true);
socket.addHandshakeCompletedListener(handshakeCompletedEvent -> {
try{
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.println("Setup"); writer.flush();
while(running){
if(!socket.isConnected() || socket.isClosed()){
disconnect();
return;
}
for(Iterator<String> pendingIterator = pendingMessages.iterator(); pendingIterator.hasNext();){
String message = pendingIterator.next();
pendingIterator.remove();
writer.println(message); writer.flush();
}
//Auto decrypt when message arrives, but no thread blocking
if(reader.ready()){
String line = reader.readLine();
System.out.println(line);
}
}
}catch(Exception e){
e.printStackTrace();
}
});
socket.startHandshake();
}catch(Exception e){
e.printStackTrace();
disconnect();
}
Client:
socket.addHandshakeCompletedListener(new HandshakeCompletedListener(){
#Override
public void handshakeCompleted(HandshakeCompletedEvent handshakeCompletedEvent){
try{
Log.i("Update", "Did handshake");
writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
writer.flush();
Log.i("Update", "Writer");
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.i("Update", "Reader");
while(isRunning){
try{
writer.println("Test");
writer.flush();
Log.i("DATA", "DATA SENT");
}catch(Exception e){
e.printStackTrace();
}
}
writer.close();
reader.close();
socket.close();
}catch(Exception e){
e.printStackTrace();
}
}
});
socket.startHandshake();
You are misusing the handshake completed listener. Its purpose is to let to check he peer certificate, negotiated cipher suite, etc. Not to carry out the transaction. Remove it all and put it inline. You don't need even to call startHandshake(). It will happen automatically on the first I/O.
I tried to write a simple program that runs a server and then accepts two clients. Then one of them tries to send a string to another client.
but my code doesn't work and I don't know why.
This is my TestClient class:
public class TestClient extends Thread{
int id;
String Name;
Socket client;
boolean isAsk;
public TestClient(int id,String clientName,boolean isAsk) throws IOException {
this.id=id;
this.Name=clientName;
this.isAsk=isAsk;
}
public void connectTheClientToTheLocalHost(ServerSocket server){
try {
client = new Socket("localhost",1111);
server.accept();
} catch (IOException e) {
e.printStackTrace();
}
}
public void readFromTerminal(){
try {
InputStream is=client.getInputStream();
OutputStream os = client.getOutputStream();
PrintWriter pw = new PrintWriter(os);
pw.println("sdklfsdklfk");
pw.flush();
pw.close();
}catch (IOException e){
e.printStackTrace();
}
}
public void closeTheCientSocket(){
try {
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void write(){
try {
Scanner sc = new Scanner(client.getInputStream());
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("file1.txt")));
String st =sc.nextLine();
bw.write(st);
bw.close();
}catch (IOException e){
e.printStackTrace();
}
}
#Override
public void run() {
if(isAsk){
readFromTerminal();
}
else{
write();
}
}
and this is the main function:
public class PCServer {
public static void main(String[] args){
try {
ServerSocket s = new ServerSocket(1111);
TestClient t1=(new TestClient(1,"reza",true));
TestClient t2=(new TestClient(2,"man",false));
t1.connectTheClientToTheLocalHost(s);
t1.start();
Scanner sc = new Scanner(t1.client.getInputStream());
String st=sc.nextLine();
System.out.println(st);
t1.closeTheCientSocket();
t2.connectTheClientToTheLocalHost(s);
PrintWriter pw = new PrintWriter(t2.client.getOutputStream());
pw.println(st);
pw.flush();
t2.start();
t2.closeTheCientSocket();
}catch (Exception e){
e.printStackTrace();
}
}
}
actually this code returns an exception in
String st=sc.nextLine();
in main function and says that there is no line found.
what is the problem?
ServerSocket in java usually used in another way.
If you need point-to-point connection, one host creates a ServerSocket and accepts connections. Examples:
First host example:
try(ServerSocket serverSocket = new ServerSocket(5555);
Socket socket = serverSocket.accept();
// it more convenient to use DataInputStream instead of Scanner I think
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());) {
while (!Thread.currentThread().isInterrupted()) {
String msg = dataInputStream.readUTF();
System.out.println("got request: " + msg);
dataOutputStream.writeUTF("1-response");
dataOutputStream.flush();
}
} catch (IOException e) {
e.printStackTrace();
}
Second host example:
try(Socket socket = new Socket("127.0.0.1", 5555);
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream())) {
while (!Thread.currentThread().isInterrupted()) {
dataOutputStream.writeUTF("2-request");
dataOutputStream.flush();
String msg = dataInputStream.readUTF();
System.out.println("got response: " + msg);
}
} catch (IOException e) {
e.printStackTrace();
}
If you want one host talk to another over the server (broker), then you need plane java Sockets on hosts and ServerSocket on broker, and broker must transmit messages it received from one host to another. Examples:
Broker (run it in separate thread or process)
try {
List<Socket> sockets = new ArrayList<>();
ServerSocket serverSocket = new ServerSocket(5555);
// accepting connections from 2 clients
for (int i = 0; i < 2; i++) {
Socket socket = serverSocket.accept();
sockets.add(socket);
}
// streams for first host
InputStream hostOneInputStream = sockets.get(0).getInputStream();
DataInputStream hostOneDataInputStream = new DataInputStream(sockets.get(0).getInputStream());
DataOutputStream hostOneDataOutputStream = new DataOutputStream(sockets.get(0).getOutputStream());
// streams for second host
InputStream hostTwoInputStream = sockets.get(1).getInputStream();
DataInputStream hostTwoDataInputStream = new DataInputStream(sockets.get(1).getInputStream());
DataOutputStream hostTwoDataOutputStream = new DataOutputStream(sockets.get(1).getOutputStream());
while (!Thread.currentThread().isInterrupted()) {
if (hostOneInputStream.available() > 0) {
String msg = hostOneDataInputStream.readUTF();
System.out.println("got message from host 1: " + msg);
hostTwoDataOutputStream.writeUTF(msg);
hostTwoDataOutputStream.flush();
System.out.println("message " + msg + " sent to host two");
}
if (hostTwoInputStream.available() > 0) {
String msg = hostTwoDataInputStream.readUTF();
System.out.println("got message from host 2: " + msg);
hostOneDataOutputStream.writeUTF(msg);
hostOneDataOutputStream.flush();
System.out.println("message " + msg + " sent to host one");
}
}
} catch (IOException e) {
e.printStackTrace();
}
First host (run it in separate thread or process)
try(Socket socket = new Socket("127.0.0.1", 5555);
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream())) {
while (!Thread.currentThread().isInterrupted()) {
dataOutputStream.writeUTF("1");
dataOutputStream.flush();
String msg = dataInputStream.readUTF();
System.out.println("got msg: " + msg);
TimeUnit.SECONDS.sleep(5);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
Second host (run it in separate thread or process)
try(Socket socket = new Socket("127.0.0.1", 5555);
DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream())) {
while (!Thread.currentThread().isInterrupted()) {
String msg = dataInputStream.readUTF();
System.out.println("got msg: " + msg);
TimeUnit.SECONDS.sleep(5);
dataOutputStream.writeUTF("2");
dataOutputStream.flush();
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
I am using a data generator which uses ports for streaming data. I use multiple ports mfor receiving data. The software I am writing makes a new socket for each port. Every socket should make an instance of a class called 'Interpreter'.
The problem I have is the following: I am able to make multiple instances of Interpreter, but I think the data is all being parsed to only one of the instances. I think this happens because the data is 'merged' in the output.
This is the most important snipet of the code:
public class Main {
public static void main (String[] args) {
Socket socket;
ServerSocket serverSocket=null;
System.out.println("Server Listening..");
try{
serverSocket = new ServerSocket(7789);
}
catch(IOException e){
e.printStackTrace();
System.out.println("Error");
}
while(true){
try{
socket= serverSocket.accept();
Interpreter interp = new Interpreter();
ServerThread serverThr=new ServerThread(socket, interp);
serverThr.start();
}
catch(Exception e){
e.printStackTrace();
System.out.println("Connection Error");
}
}
}
}
class ServerThread extends Thread {
String line = null;
BufferedReader is = null;
PrintWriter os = null;
Socket s = null;
public ServerThread(Socket s, Interpreter interp) {
this.interp = interp;
this.s = s;
System.out.println("interp "+interp);
System.out.println("s: "+s);
System.out.println("poort: "+s.getPort());
}
public void run() {
try {
is = new BufferedReader(new InputStreamReader(s.getInputStream()));
os = new PrintWriter(s.getOutputStream());
} catch (IOException e) {
System.out.println("IO error in server thread");
}
try {
line = is.readLine();
while (line.compareTo("QUIT") != 0) {
os.println(line);
os.flush();
Interpreter.interpreter(line);
line = is.readLine();
}
} catch (IOException e) {
line = this.getName();
System.out.println("IO Error/ Client " + line + " terminated abruptly");
} catch (NullPointerException e) {
line = this.getName();
System.out.println("Client " + line + " Closed");
} finally {
try {
System.out.println("Connection Closing..");
if (is != null) {
is.close();
System.out.println(" Socket Input Stream Closed");
}
if (os != null) {
os.close();
System.out.println("Socket Out Closed");
}
if (s != null) {
s.close();
System.out.println("Socket Closed");
}
} catch (IOException ie) {
System.out.println("Socket Close Error");
}
}
}
}
This is the 'important' part of Interpreter:
public class Interpreter{
static AtomicInteger nextId = new AtomicInteger();
int id = nextId.incrementAndGet();
public Interpreter(){
System.out.println("ID of demo "+id);
}
}
I am working on a java socket program and have difulcites with the client part. The server get's what all the clients write, but the client only gets what it writes. Could someone provide me with an example of a client part of a program that gets what all the clients write? Thanks!
Here is an "echo server" example
import java.io.*;
import java.net.*;
class TCPServer
{
public static void main(String argv[]) throws IOException
{
ServerSocket serverSocket = null;
DataInputStream serverInput = null;
PrintStream serverOutput = null;
String line = null;
Socket clientSocket = null;
// create server socket
try
{
serverSocket = new ServerSocket(2012);
clientSocket = serverSocket.accept();
serverInput = new DataInputStream(clientSocket.getInputStream());
serverOutput = new PrintStream(clientSocket.getOutputStream());
}
catch(IOException e){System.out.println(e);}
// receive data and send it back to the client
try
{
while(true)
{
line = serverInput.readLine();
if(line.equals("exit"))
{
break;
}
else
{
if(!line.equals(null) && !line.equals("exit"))
{
System.out.println("Received " +line);
line = line+" MODIFIED";
serverOutput.println(line);
}
}
}
}
catch(IOException e){System.out.println("SERVER SIDE: Unable send/receive data");}
try
{
serverInput.close();
serverOutput.close();
clientSocket.close();
serverSocket.close();
}
catch(IOException e){System.out.println(e);}
}
}
Here is the client
import java.io.*;
import java.net.*;
public class TCPClient
{
public static void main(String[] args) throws IOException
{
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
try {
echoSocket = new Socket("localhost", 2012);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(echoSocket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host");
System.exit(1);
} catch (IOException e) {
System.err.println("Couldn't get I/O");
System.exit(1);
}
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println(userInput);
System.out.println("echo: " + in.readLine());
if(userInput.equals("exit"))
break;
}
out.close();
in.close();
stdIn.close();
echoSocket.close();
}
}
how to reuse TCP Socket connection(possible setReuseAddress(true), but not work for me) for download multiple files from Server(Apache, HTTPD) in on connection without disconnect(and connect again).
My code below..
public class ClientThread implements Runnable {
public void run() {
try {
Log.d("ClientActivity", "C: Connecting...");
SocketAddress sockaddr = new InetSocketAddress(serverIpAddress, SERVERPORT);
socket = new Socket();
socket.setReuseAddress(true);
socket.setKeepAlive(true);
socket.setSoLinger(true, 3000);
socket.connect(sockaddr);
if (socket.isConnected()) {
DataInputStream input = new DataInputStream(socket.getInputStream());
PrintWriter output = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
output.println("GET /way/images/profile/1231 HTTP/1.1");
output.println("Host: 192.168.1.2");
output.println("User-Agent: Java");
output.println("Accept: */*");
output.println("Connection: Keep-Alive");
output.println("");
output.flush();
String line;
File file = new File("/sdcard/aaa.png");
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fileOut = new FileOutputStream(file);
System.out.println("Getting first file");
while ( (line = input.readLine()) != null ) {
System.out.println(line);
fileOut.write(line.getBytes());
}
System.out.println("First file finished");
fileOut.flush();
fileOut.close();
output.println("GET /way/images/profile/1231 HTTP/1.1");
output.println("Host: 192.168.1.2");
output.println("User-Agent: Java");
output.println("Accept: */*");
output.println("Connection: Keep-Alive");
output.println("");
output.flush();
file = new File("/sdcard/aaa1.png");
if (!file.exists()) {
file.createNewFile();
}
fileOut = new FileOutputStream(file);
System.out.println("Getting second file");
while ( (line = input.readLine()) != null ) {
System.out.println(line);
fileOut.write(line.getBytes());
}
System.out.println("Second file finished");
fileOut.flush();
fileOut.close();
input.close();
output.close();
}
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
finally {
try {
Log.d("ClientActivity", "Socket: Closed.");
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Thanks...
setReuseAddress(true) prior to binding the socket allows the socket to be bound even though a previous connection is in a timeout state.
documentation of setReuseAddress
I don't see sense in directly using socket for HTTP communication. I use HttpURLConnection. Works without problems in most cases.