i have this code to do chatting
but it did not work , but somebody told me that i should use byte array and a string but i did not understand i hope you can help me to fix this problem , this code belongs to the server...
public void run() {
try {
ServerSocket= new ServerSocket(44444);//inside there is the port mumber which will be gain later from firstscreen
ClientSocket= ServerSocket.accept();
OUT= new ObjectOutputStream(ClientSocket.getOutputStream());
IN=new ObjectInputStream(ClientSocket.getInputStream());
while (true){
Object input =IN.readObject();
textArea.setText(textArea.getText()+"Client:"+(String)input+"\n");//update the textarea
}//loop end
}catch (IOException e){
//joptionpane
e.printStackTrace();
} catch (ClassNotFoundException e) {
//joptionpane
e.printStackTrace();
}
}//end of try
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("Send")|| e.getSource() instanceof JTextField){
try {
if(textField.getText().isEmpty()) {
OUT.writeObject(textField.getText());
textArea.setText(textArea.getText()+"Assistant:"+textField.getText()+"\n");}
}
catch (IOException c){
c.printStackTrace();
}
}
I hope you understand that you are only letting just a SINGLE client connect to the server, since there cannot happen any other serverSocket.accept()
First, you are only sending the information if the textfield text is empty at if(textField.getText().isEmpty()) which is quite a nonsense, otherwise there is no call to send through socket any data.
Apart from this, I do not see the code for the actionPerformed block, which I assume you have coded it before with a JButton or so and implementing the jbutton.addActionListener()
Also, I hope ClientSocket is a class of your own, because a client is represented as a Socket, not ClientSocket.
On the other hand, I would suggest the following API writeUTF and forget about needing to cast the string into bytes or otherways, with the help of DataInput and DataOutputStreams.
The code would be left as:
public void run() {
try {
ServerSocket serverSocket= new ServerSocket(44444);//inside there is the port mumber which will be gain later from firstscreen
Socket clientSocket= serverSocket.accept();
DataOutputStream OUT = new DataOutputStream(clientSocket.getOutputStream());
DataInputStream IN = new DataInputStream(clientSocket.getInputStream());
while (true){
String input = IN.readUTF();
textArea.append(input+"\n"); //update the textarea
}//loop end
}catch (IOException e){
//joptionpane
e.printStackTrace();
} catch (ClassNotFoundException e) {
//joptionpane
e.printStackTrace();
}
}//end of try
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals("Send")|| e.getSource() instanceof JTextField) {
try {
if(!textField.getText().isEmpty()) { //Do not forget to include the ! (NOT)
OUT.writeUTF(textField.getText());
textArea.setText(textArea.getText()+"Assistant:"+textField.getText()+"\n");
}
}
catch (IOException c){
c.printStackTrace();
}
}
}
I hope to have been able to have helped you.
Related
It's my first question in here. I hope i can find answer. Subject is that, i have server (arduino). it send and receive data.it send data when take a data from client side(android). Android side is send data when push button. Also android has use Speech to Text (google API).So when we push button or use speechrecognation, client side send a data.But it reads socket continuously. I have two kind android device. One device work well about data receiving but it is not good about speechrecognation. One device very well about voice but after a while socket is happened useless. We must push reset button on arduino and reset android app. (My first android device version is 5.1.1 second is 6.0). Sorry for my english. I hope i can tell my problem :)
.
.
.
public void senddata(String asd){
try {
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(asd);
out.flush();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
.
.
.
class ClientThread implements Runnable {
#Override
public void run() {
BufferedReader inStream = null;
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
//socket.setSoTimeout(1000);
// Get the input and output streams
inStream = new BufferedReader(new
InputStreamReader(socket.getInputStream()));
// Confirm that the socket opened
// Read messages in a loop until disconnected
while( true){
String msg= inStream.readLine();
Log.e("GELENLER::::",msg);
gelenkomut=msg;
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
gelenparse(gelenkomut);
}
});
// Send it to the UI thread
}
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
finally {
try {
inStream.reset();
inStream.
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
How do you make a client which is able to send a server multiple messages at anytime, and therefore a server listening for a message all the time.
Right now I have wrote some code which only allows me to send a message once. I thought this was due to me closing the input/output streams and the sockets. So I have been playing around for a while now and I can't seem to do it!
Client:
public class Client {
private Socket socket;
private OutputStream os;
public Client() {}
public void connectToServer(String host, int port) {
try {
socket = new Socket(host, port);
} catch (IOException e) {
e.printStackTrace();
}
sendMessage();
}
public void sendMessage() {
try {
os = socket.getOutputStream();
String string = "Anthony";
byte[] b = string.getBytes(Charset.forName("UTF-8"));
os.write(b);
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void STOP() {
stopOutput();
stopServer();
}
public void stopServer() {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void stopOutput() {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Server:
public class ConnectionHandler implements Runnable {
private Socket clientSocket;
private BufferedReader in;
public ConnectionHandler(Socket clientSocket) {
this.clientSocket = clientSocket;
String clientAddress = clientSocket.getInetAddress().toString()
.substring(1);
System.out.println("Connected to " + clientAddress);
try {
in = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
while (true) {
try {
ArrayList<String> data = new ArrayList<String>();
String inputLine;
while ((inputLine = in.readLine()) != null) {
data.add(inputLine);
}
if (data.size() > 0) {
System.out.println(data.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void STOP() {
stopInput();
stopConnection();
}
public void stopInput() {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void stopConnection() {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
At the moment on the client side, I send a message as soon as the socket is opened but after when I call the send function from another class it does not send...
How should I do this? Or what am I doing wrong?
Thanks in advance.
p.s. I am guessing client-server is the same as server-client, so if I know how to do one way I can easily switch it around... right?
Turns outs it was a simple error.
I as writing (sending-client) as an OutputStream however I was then reading (receiving-server) as BufferedReader! ha
So quick tip for anyone, make sure you receive messages the same way you send them!
Thanks for everyone who tried helping.
Your server is accepting data all the time, so you just have to save the OutputStream of you Client somewhere and write data to it every now and then. But do not close it, because then you close the Client socket, too.
After you have done that, you would need to change something else, because now your call of in.readLine() blocks your server, because it waits for the client to send something. To prevent that, you could try to add sending a String like "close" to the server when you want to close your client, something like that:
public void STOP() {
os.write("close".getBytes(Charset.forName("UTF-8")));
stopOutput();
stopServer();
}
and change the code in your server to
try {
ArrayList<String> data = new ArrayList<String>();
String inputLine;
while (!(inputLine = in.readLine()).equals("close")) {
data.add(inputLine);
}
if (data.size() > 0) {
System.out.println(data.toString());
}
} catch (IOException e) {
e.printStackTrace();
}
I was learning tcp/ip protocol and i wrote a program yesterday. It's a simple code , client send a string, server receive and print it to console . but when i start , this become error . Anyone check it for me , please . Here's my code .
Client side :
public class Client {
Socket client ;
DataInputStream is;
DataOutputStream os;
public Client(){
try {
client=new Socket("localhost", 7777);
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void send(String txt){
try {
os=new DataOutputStream(client.getOutputStream());
if(os!=null && client!=null)
os.writeBytes(txt);
System.out.println("Send OK");
close();
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void close(){
if(client!= null&& os!= null&& is!= null) {
try{
os.close();
is.close();
client.close();
}
catch(UnknownHostException e) {
System.err.println(e);
} catch(IOException e) {
System.err.println(e);
}}}}
Client main :
public static void main(String[] args) {
// TODO code application logic here
Client client=new Client();
client.send("hehea");
}
and the server :
public class ServerTCP {
PrintStream os;
DataInputStream is;
Socket client;
ServerSocket myserver;
public void open(){
try {
myserver=new ServerSocket(7777);
System.out.println("Open Server ");
client=myserver.accept();
listen();
} catch (IOException ex) {
Logger.getLogger(ServerTCP.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void listen(){
try {
System.out.println("\nListenning....");
is=new DataInputStream(client.getInputStream());
os=new PrintStream(client.getOutputStream());
String txt="";
ReverseString result = null;
while(true)
{
result=new ReverseString(is.readLine());
System.out.println(is.readLine());
}
} catch (IOException ex) {
Logger.getLogger(ServerTCP.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Server main
public static void main(String[] args) {
// TODO code application logic here
ServerTCP server=new ServerTCP();
server.open();
Finally , error in console
java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:196)
at java.net.SocketInputStream.read(SocketInputStream.java:122)
at java.net.SocketInputStream.read(SocketInputStream.java:210)
at java.io.DataInputStream.readLine(DataInputStream.java:513)
at daochuoiservertcp.ServerTCP.listen(ServerTCP.java:50)
at daochuoiservertcp.ServerTCP.open(ServerTCP.java:34)
at daochuoiservertcp.Server.main(Server.java:21)
You're reading lines but you aren't sending lines. You need to add a \n at least to the end of the sent message.
You're reading infinitely and not checking for end of stream. The readLine() method returns null when the peer has disconnected. At the point you must exit the read loop and close the socket.
You're reading twice per iteration. That will attempt to read two separate lines from the input. It won't give you the same line twice. It seems pointless.
It's caused by the server or client close the connection when the other side haven't finish the IO operation. It'd better if you can paste the both main methods here. Then we can check it further
Getting error NullPointerException while trying to identify if serialized object is available and receive it using socket. How to identify if ObjectInputStream has available object?
Firs off I try to read a text then try to read from the same socket Lot object ()which may not be there.
public class ThreadIn extends Thread{
BufferedReader in;
PrintStream outConsole;
Socket socket;
ObjectInputStream ois;
String str;
Lot lot;
ThreadIn(BufferedReader input, PrintStream inOutput, Socket s){
str = "";
in= input;
socket= s;
try {
ois = new ObjectInputStream(socket.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
outConsole = inOutput;
}
public void run() {
while(!EXIT_THREAD){
try {
if(in.ready()){
try {
str= in.readLine();
Thread.sleep(100);
} catch (IOException e) {
EXIT_THREAD= true;
break;
} catch (InterruptedException e) {
e.printStackTrace();
}
outConsole.println("Received:"+str);
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if((Lot)ois.readObject() != null){
lot = (Lot)ois.readObject();
if (lot!=null){outConsole.println(lot.toString());}
outConsole.println((String)ois.readObject());
}
} catch (Exception e) {
e.printStackTrace();
}
}
if((Lot)ois.readObject() != null)
this part itself reads the object from Socket., So you are reading 3 times the object from Socket in your code. If you have only one Object coming in the socket, or more, you can read the object and catch the exception!.
Just like below
//..loop start
try {
lot = (Lot)ois.readObject();
}
catch (Exception e)
{
// do some handling, skip the object! put a continue: or something
}
//do what ever you want to do with `lot`
//..loop end
and now, as per your code, you have not initialized your ObjectInputStream Object.
Do a ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
If you omitted the code here, well my mistake, else pls do initialize the socket also!
As per the other answers, including the deleted ones, you are calling readObject() twice and throwing the first result away. You should reorganize your code so it can block in readObject().
You have other problems. You are testing the result of readObject() for null?, but it only returns null if you wrote a null at the sender. I suspect you are using this as an EOS test, but it is invalid. readObject() throws EOFException at EOS. You should reorganize your code so it can block in readObject().
Sorry for question, but I'm totally noob in Java. What is the best practice to execute ServerSocket.close() when caught IOException from ServerSocket? According to docs, ServerSocket.close() throws IOException and compiler asks us to catch it. What is the proper way to close connection on IOException?
try {
server = new ServerSocket(this.getServerPort());
while(true) {
socket = server.accept();
new Handler( socket );
}
} catch (IOException e) {
if (server != null && !server.isClosed()) {
server.close(); //compiler do not allow me to do because I should catch IOExceoption from this method also...
}
}
Thank you!
That's ugly in Java. I hate it, but this is the way you should do it: Wrapping it into another try-catch:
try {
server = new ServerSocket(this.getServerPort());
while(true) {
socket = server.accept();
new Handler( socket );
}
} catch (IOException e) {
if (server != null && !server.isClosed()) {
try {
server.close();
} catch (IOException e)
{
e.printStackTrace(System.err);
}
}
}
If you are going to close the ServerSocket outside of the try{}catch{} anyways, you may as well put it in a finally{}
try {
server = new ServerSocket(this.getServerPort());
while(true) {
socket = server.accept();
new Handler( socket );
}
} catch (IOException e) {
// Do whatever you need to do here, like maybe deal with "socket"?
}
finally {
try {
server.close();
} catch(Exception e) {
// If you really want to know why you can't close the ServerSocket, like whether it's null or not
}
}
In Java SE 7 or later you can use try-with-resources statement, ServerSocket implements java.io.Closeable, so you don't need to explicitly #close() the socket when used in this way.
try (ServerSocket server = new ServerSocket(this.getServerPort())) {
while(true) {
socket = server.accept();
new Handler( socket );
}
} catch (IOException e) {
// It's already closed, just print the exception
System.out.println(e);
}
You can close the resources in the finally block,
http://download.oracle.com/javase/tutorial/essential/exceptions/finally.html
} finally {
try {
socket.close();
} catch(IOException e) {
e.printStackTrace();
}
}