When the code reaches the InputStream.read(), the application becomes iresponsive.
I think maybe that is the case because the client code runs before the server code and it waits for the input.
Here is the server code
When login button is clicked then the case is "Send login details"(It sends the login details to the client) and if the id and password is correct then the case becomes**"Login successful". It is sending correct value in **output.readUTF();
public void doWork(String line) {
Connection conn = Main.getConnection();
switch (line) {
case "Send login details":
Main main = new Main();
String details = main.giveLoginDetails();
String id = " ";
String password = " ";
int i = 0;
while (details.charAt(i) != ' ') {
id = id + details.charAt(i);
i++;
}
try {
id = id.trim();
password = details.substring(i + 1);
System.out.println(id + " " + password);
output.writeUTF(id + " " + password);
}
catch (IOException e)
{
e.printStackTrace();
}break;
case "Login successful":
String getDet1 = "SELECT * FROM $t;";
if(su == 1)
getDet1 = getDet1.replace("$t", "Post1");
else
getDet1 = getDet1.replace("$t", "Post"+(su*10+1));
System.out.print(getDet1);
rs2 = stmt2.executeQuery(getDet1);
String d;
int dd;
for (int x = 0; x < ch; x++) {
rs2.next();
d = rs2.getString(2);
output.writeUTF(d);
System.out.println(d);
dd = rs2.getInt(3);
output.writeInt(dd);
System.out.println(dd);
d = rs2.getString(4);
output.writeUTF(d);
System.out.println(d);
d = rs2.getString(5);
// if(d == null) {
// output.writeUTF("null");
// System.out.println("null");
// }
// else
output.writeUTF(d);
// System.out.println(d+"not null ");}
}
}
catch (SQLException | IOException e) {
e.printStackTrace();
}
break;
}
}
Client code:- Another scene after the login scene.
It is the Initialize method of Initializable interface. Here i am reading the output but it hangs.
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
String posts = "";
int ch = 0;
Main m = new Main();
Stage stage = m.getStage();
stage.setResizable(true);
int c = 0;
try {
posts = Networking.input.readUTF();
ch = Networking.input.readInt();
}
catch (IOException e)
{
e.printStackTrace();
}
int rs = Integer.valueOf(posts);
for(int k = 0; k<rs; k++) {
c++;
}
try {
Networking.input.readUTF();
}
catch (IOException e)
{
e.printStackTrace();
}
String det = "";
int cl;
for (int i = 0; i < ch; i++) {
a[i].setDisable(false);
a[i].setOpacity(1);
try {
Networking.output.writeUTF("send voting details");
det = Networking.input.readUTF();
System.out.println(det);
cl = Networking.input.readInt();
System.out.println(cl);
det = Networking.input.readUTF();
System.out.println(det);
det = Networking.input.readUTF();
System.out.println(det);
}
catch (IOException exx)
{
exx.printStackTrace();
}
}
}
Add:
Here is my Networking class
package sample;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Networking {
public static ServerSocket serverSocket= null;
public static void connect(int port)
{
try
{
serverSocket = new ServerSocket(port);
System.out.print("Server is started");
while (true)
{
Socket socket = null;
try {
socket = serverSocket.accept();
DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
Thread thread = new ServerThread(socket, input, output);
thread.start();
System.out.print("Client Accepted");
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
catch(IOException exception)
{
exception.printStackTrace();
}
}
}
I tried to create exe file from my code but it's get me error
java.lang.ClassNotFoundException: Access2
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
I used exe4j tool to generate exe from jar file
I used Jdk 1.8.0_25
and this a part of my main class (Access2)
public class Access2
{
BufferedReader in;
Writer out;
String CommData = "";
String TextData = "";
int FrameNo = 1;
String STX = String.valueOf('\002');
String ETX = String.valueOf('\003');
String EOT = String.valueOf('\004');
String ENQ = String.valueOf('\005');
String ACK = String.valueOf('\006');
String LF = String.valueOf('\n');
String CR = String.valueOf('\r');
String DEL = String.valueOf('\007');
String NAK = String.valueOf('\025');
String SYN = String.valueOf('\026');
String ETB = String.valueOf('\027');
String CRLF = this.CR + this.LF;
String enc;
String LastType = "";
String PatientID;
String PatientName;
String SampleID;
String Result = "";
String Parameter = "";
String PatientComment;
String SampleComment;
String ResultComment = "";
String QuerySampleID;
boolean QueryAsked = false;
Connection connection = null;
Statement stmt = null;
PreparedStatement prepStatement = null;
ResultSet rs = null;
String machine = Setting.GetPropVal("MachineName");
ArrayList<String> DataToSend = new ArrayList();
int Max_Farme_Size = 240;
int FIndex = 1;
int CurIndex = 0;
int RowIndex = 1;
String Frame_Sep;
int retries = 6;
Connection connection2 = null;
Statement stmt2 = null;
PreparedStatement prepStatement2 = null;
ResultSet rs2 = null;
public Access2(Socket s)
{
try
{
this.enc = Setting.GetPropVal("Encoding");
this.in = new BufferedReader(new InputStreamReader(s.getInputStream(), this.enc));
this.out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream(), this.enc));
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, e, "IOException", 1);
System.exit(0);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e, "Exception", 1);
System.exit(0);
}
}
public Access2(SerialPort ser)
{
try
{
this.enc = Setting.GetPropVal("Encoding");
this.in = new BufferedReader(new InputStreamReader(ser.getInputStream(), this.enc));
this.out = new BufferedWriter(new OutputStreamWriter(ser.getOutputStream(), this.enc));
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, e, "IOException", 1);
System.exit(0);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e, "Exception", 1);
System.exit(0);
}
}
public void NextFrameNo()
{
this.FrameNo += 1;
if (this.FrameNo > 7) {
this.FrameNo = 0;
}
}
public void SaveData(String data)
{
String data2save = data.replaceAll(this.ENQ, "<ENQ>").replaceAll(this.STX, "<STX>").replaceAll(this.ETX, "<ETX>").replaceAll(this.EOT, "<EOT>").replaceAll(this.CR, "<CR>").replaceAll(this.CRLF, "<CRLF>").replaceAll(this.ETB, "<ETB>");
LogFile.createLog(this.machine + "_" + CurrentDate.getDate(2) + ".txt", "\r\n[" + CurrentDate.getDate(1) + "]" + ":" + data2save);
}
public String[] ParseFrames(String Data)
{
String[] Frame = Data.split(this.CR);
return Frame;
}
public boolean CheckSumCorrect()
{
String Frame = GetFrameData(this.CommData, 1);
String CalculatedSum = GetCheckSum(Frame);
String FrameSum = GetFrameData(this.CommData, 3);
boolean Status = CalculatedSum.equals(FrameSum);
return Status;
}
public boolean CheckFarmeNum()
{
String FN = GetFrameData(this.CommData, 4);
boolean Status;
if (Integer.toString(this.FrameNo).equals(FN))
{
Status = true;
NextFrameNo();
}
else
{
Status = false;
}
return Status;
}
public String GetCheckSum(String Dat)
{
int x = 0;
for (int i = 0; i < Dat.length(); i++) {
x += Dat.charAt(i);
}
String S = "00" + Integer.toHexString(x % 256);
String CheckSum = S.substring(S.length() - 2).toUpperCase();
return CheckSum;
}
public String GetFrameData(String Data, int FrameType)
{
String Frame = "";
int pos1 = Data.indexOf(this.STX);
int pos2 = Data.indexOf(this.ETX);
int pos3 = Data.indexOf(this.ETB);
if (FrameType == 1)
{
if (Data.contains(this.ETX)) {
Frame = Data.substring(pos1 + 1, pos2 + 1);
} else if (Data.contains(this.ETB)) {
Frame = Data.substring(pos1 + 1, pos3 + 1);
}
}
else if (FrameType == 2)
{
if (Data.contains(this.ETX)) {
Frame = Data.substring(pos1 + 2, pos2);
} else if (Data.contains(this.ETB)) {
Frame = Data.substring(pos1 + 2, pos3);
}
}
else if (FrameType == 3)
{
if (Data.contains(this.ETX)) {
Frame = Data.substring(pos2 + 1, pos2 + 3);
} else if (Data.contains(this.ETB)) {
Frame = Data.substring(pos3 + 1, pos3 + 3);
}
}
else if (FrameType == 4) {
Frame = Data.substring(pos1 + 1, pos1 + 2);
}
return Frame;
}
public void sendtoport(String Sample_ID)
{
try
{
int sent = 0;
for (String DataToSend1 : this.DataToSend)
{
this.out.write(DataToSend1);
this.out.flush();
SaveData(DataToSend1);
char c = (char)this.in.read();
String control = String.valueOf(c);
if (control.equals(this.ACK))
{
sent = 1;
}
else if (control.equals(this.NAK))
{
for (int x = 1; x <= this.retries; x++)
{
this.out.write(DataToSend1);
this.out.flush();
SaveData(DataToSend1);
}
sent = 0;
break;
}
}
this.DataToSend.clear();
this.FIndex = 1;
this.out.write(this.EOT);
this.out.flush();
SaveData(this.EOT);
try
{
this.connection2 = DBconnection.getConnection();
String ExecProc = "HK_Update_SCH ?,?,?";
this.connection2.setAutoCommit(false);
this.prepStatement = this.connection2.prepareStatement(ExecProc);
this.prepStatement2.setString(1, Sample_ID);
this.prepStatement2.setString(2, "Access2");
this.prepStatement2.setString(3, "");
this.prepStatement2.executeUpdate();
this.connection2.commit();
}
catch (SQLException e)
{
JOptionPane.showMessageDialog(null, e, "SQLException", 1);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e, "Exception", 1);
}
Thread.sleep(10L);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, e, "IOException", 1);
System.exit(0);
}
catch (HeadlessException|InterruptedException e)
{
JOptionPane.showMessageDialog(null, e, "Exception", 1);
System.exit(0);
}
}
public void SplitFrames(String Frame)
{
int NumSplit = Frame.length() / this.Max_Farme_Size;
for (int i = 0; i <= NumSplit; i++) {
if (i < NumSplit)
{
String part = Frame.substring(i * this.Max_Farme_Size, i * this.Max_Farme_Size + this.Max_Farme_Size);
String IntermdiateFrame = this.STX + this.FIndex + part + this.ETB + GetCheckSum(new StringBuilder().append(this.FIndex).append(part).append(this.ETB).toString()) + this.CRLF;
this.DataToSend.add(this.DataToSend.size(), IntermdiateFrame);
NextFIndexNo();
}
else
{
String part = Frame.substring(i * this.Max_Farme_Size);
String LastFrame = this.STX + this.FIndex + part + this.ETX + GetCheckSum(new StringBuilder().append(this.FIndex).append(part).append(this.ETX).toString()) + this.CRLF;
this.DataToSend.add(this.DataToSend.size(), LastFrame);
NextFIndexNo();
}
}
}
public void NextFIndexNo()
{
this.FIndex += 1;
if (this.FIndex > 7) {
this.FIndex = 0;
}
}
public void SendOrder(String[] OrderFrame)
{
this.DataToSend.clear();
this.DataToSend.add(0, this.ENQ);
for (int i = 0; i < OrderFrame.length; i++) {
if (OrderFrame[i].length() > this.Max_Farme_Size)
{
SplitFrames(OrderFrame[i]);
}
else
{
String SingleFrame = this.STX + this.FIndex + OrderFrame[i] + this.ETX + GetCheckSum(new StringBuilder().append(this.FIndex).append(OrderFrame[i]).append(this.ETX).toString()) + this.CRLF;
this.DataToSend.add(this.DataToSend.size(), SingleFrame);
NextFIndexNo();
}
}
}
public void SendOrderData(String SampleData, String TestCodes)
{
HeaderRecord HRec = new HeaderRecord();
PatientRecord PRec = new PatientRecord();
OrderRecord ORec = new OrderRecord();
MessageTerminatorRecord LRec = new MessageTerminatorRecord();
PRec.SetPropertyValue("PracticePatientID", SampleData);
PRec.SetPropertyValue("LabPatientID", SampleData);
PRec.SetPropertyValue("PatientSex", "M");
ORec.SetPropertyValue("SampleID", SampleData);
ORec.SetPropertyValue("ActionCode", "N");
ORec.SetPropertyValue("UniversalTestID", "^^^" + TestCodes.replace(",", "\\^^^"));
ORec.SetPropertyValue("SampleType", "Serum");
ORec.SetPropertyValue("ReportTypes", "O");
String[] records = new String[4];
records[0] = HRec.FormatFrame();
records[1] = PRec.FormatFrame();
records[2] = ORec.FormatFrame();
records[3] = LRec.FormatFrame();
String Msg = HRec.FormatFrame() + PRec.FormatFrame() + ORec.FormatFrame() + LRec.FormatFrame();
System.out.println(">>>>>>>>" + Msg);
try
{
SendOrder(records);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e, "Exception", 1);
System.exit(0);
}
}
public void FramesReady(String[] Frame)
{
}
public void ManageData()
{
try
{
if (this.CommData.contains(this.ENQ))
{
SaveData(this.CommData);
this.CommData = "";
this.out.write(this.ACK);
this.out.flush();
}
else if (this.CommData.contains(this.CRLF))
{
SaveData(this.CommData);
if ((CheckSumCorrect()) && (CheckFarmeNum()))
{
this.TextData += GetFrameData(this.CommData, 2);
this.CommData = "";
this.out.write(this.ACK);
this.out.flush();
}
else if ((!CheckSumCorrect()) || (!CheckFarmeNum()))
{
this.CommData = "";
this.out.write(this.NAK);
this.out.flush();
}
}
else if (this.CommData.contains(this.EOT))
{
SaveData(this.CommData);
String[] x = ParseFrames(this.TextData);
FramesReady(x);
this.TextData = "";
this.FrameNo = 1;
this.CommData = "";
}
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, e, "IOException", 1);
System.exit(0);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e, "Exception", 1);
System.exit(0);
}
}
public void Server()
{
try
{
for (;;)
{
char c = (char)this.in.read();
System.out.print(c);
this.CommData += c;
ManageData();
}
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, e, "IOException", 1);
System.exit(0);
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e, "Exception", 1);
System.exit(0);
}
}
public static void main(String[] args)
throws Exception
{
switch (Setting.GetPropVal("Socket"))
{
case "TCPIP":
String IP = Setting.GetPropVal("IPaddress");
int Port2Rec = Integer.parseInt(Setting.GetPropVal("INport"));
InetAddress addr = InetAddress.getByName(IP);
String host = addr.getHostName();
Socket s = new Socket(host, Port2Rec);
System.out.println("Connected to :" + host + "/" + Port2Rec);
Access2 TcpChat = new Access2(s);
TcpChat.Server();
break;
case "Serial":
SerialPort serialPort = null;
Enumeration portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements())
{
CommPortIdentifier portId = (CommPortIdentifier)portList.nextElement();
if ((portId.getPortType() == 1) &&
(portId.getName().equals(Setting.GetPropVal("ComPort"))))
{
serialPort = (SerialPort)portId.open("HPS", 10);
serialPort.setSerialPortParams(9600, 8, 1, 0);
}
}
System.out.println("Connected to :" + serialPort.getName());
Access2 SerialChat = new Access2(serialPort);
SerialChat.Server();
}
}
}
when i run the program from eclipse
"Wrong Path OR file Lost" is shown
public class Setting
{
public static Properties props;
public static String propVal;
public static String GetPropVal(String param)
{
try
{
props = new Properties();
props.load(new FileInputStream("Access2.ini"));
propVal = props.getProperty(param);
}
catch (IOException e)
{
JOptionPane.showMessageDialog(null, "Wrong Path OR file Lost", "Alert", 1);
System.exit(0);
}
return propVal;
}
}
how can i solve that ? It said my class is not found but it exist what is the solution ?
This happens because of improper packaging of class files or rather, improper compilation of Java files inside a package.
Go for a build tool such as Maven with a clean directory including Java files and then generate a .jar.
Basically, if you can, create a fresh Maven or Ant project and create Java files with same names and paste the content into new ones, one by one.
EDIT: Make sure that there is only ONE public class in the main package.
I am trying to make a video streaming application between pc and android device. so I am getting this error "SocketTimeoutException"
private class ChatOperator extends AsyncTask<Void, Void, Void> {
DatagramPacket rcvdp;
DatagramSocket RTPsocket;
int RTP_RCV_PORT = 25000;
Timer timer;
byte[] buf;
final static int INIT = 0;
final static int READY = 1;
final static int PLAYING = 2;
int state;
Socket RTSPsocket;
BufferedReader RTSPBufferedReader;
BufferedWriter RTSPBufferedWriter;
String VideoFileName;
int RTSPSeqNb = 0;
int RTSPid = 0;
final static String CRLF = "\r\n";
int MJPEG_TYPE = 26;
#Override
protected Void doInBackground(Void... params) {
buf = new byte[15000];
int RTSP_server_port = 4444;
String ServerHost = "10.0.3.2";
try {
InetAddress ServerIPAddr = InetAddress.getByName(ServerHost);
VideoFileName = "media/movie.Mjpeg";
RTSPsocket = new Socket(ServerIPAddr, 4444);
RTSPBufferedReader = new BufferedReader(new InputStreamReader(
RTSPsocket.getInputStream()));
RTSPBufferedWriter = new BufferedWriter(new OutputStreamWriter(
RTSPsocket.getOutputStream()));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e.toString());
}
try {
RTPsocket = new DatagramSocket(RTP_RCV_PORT);
RTPsocket.setSoTimeout(5);
} catch (SocketException se) {
System.out.println("Socket exception: " + se);
System.exit(0);
}
RTSPSeqNb = 1;
send_RTSP_request("SETUP");
if (parse_server_response() != 200)
System.out.println("Invalid Server Response");
else {
state = READY;
System.out.println("New RTSP state: READY");
}
System.out.println("Play Button pressed !");
RTSPSeqNb++;
send_RTSP_request("PLAY");
if (parse_server_response() != 200)
System.out.println("Invalid Server Response");
else {
state = PLAYING;
System.out.println("New RTSP state: PLAYING");
new java.util.Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
rcvdp = new DatagramPacket(buf, buf.length);
try {
RTPsocket.receive(rcvdp);
RTPpacket rtp_packet = new RTPpacket(rcvdp.getData(), rcvdp.getLength());
System.out.println("Got RTP packet with SeqNum # "
+ rtp_packet.getsequencenumber() + " TimeStamp "
+ rtp_packet.gettimestamp() + " ms, of type "
+ rtp_packet.getpayloadtype());
rtp_packet.printheader();
int payload_length = rtp_packet.getpayload_length();
byte[] payload = new byte[payload_length];
rtp_packet.getpayload(payload);
bmp = BitmapFactory.decodeByteArray(payload,0,payload_length);
System.out.print("a packet recieved");
} catch (IOException e) {
//e.printStackTrace();
System.out.println("Nothing Recieved");
}
}
}, 0, 200);
}
return null;
}
private int parse_server_response() {
int reply_code = 0;
try {
String StatusLine = RTSPBufferedReader.readLine();
StringTokenizer tokens = new StringTokenizer(StatusLine);
tokens.nextToken();
reply_code = Integer.parseInt(tokens.nextToken());
if (reply_code == 200) {
String SeqNumLine = RTSPBufferedReader.readLine();
String SessionLine = RTSPBufferedReader.readLine();
tokens = new StringTokenizer(SessionLine);
tokens.nextToken();
RTSPid = Integer.parseInt(tokens.nextToken());
}
} catch (Exception ex) {
}
return (reply_code);
}
private void send_RTSP_request(String request_type) {
try {
RTSPBufferedWriter.write(request_type + " " + VideoFileName + " "
+ "RTSP/1.0" + CRLF);
RTSPBufferedWriter.write("CSeq: " + RTSPSeqNb + CRLF);
if (request_type.equals("SETUP")) {
RTSPBufferedWriter.write("Transport: RTP/UDP; client_port= "
+ RTP_RCV_PORT + CRLF);
}
else {
RTSPBufferedWriter.write("Session: " + RTSPid + CRLF);
}
RTSPBufferedWriter.flush();
} catch (Exception ex) {
}
}
}
the error is made by this line of code in the timer object
RTPsocket.receive(rcvdp);
I am wondering the same code works well at java SE .
but in android it sends request to the server to run and stop but I cannot receive packets like in java SE . Thanks.
I am trying to program my own chat but I can't get the text from one client to the next. I have the chat as a list but I can't add it. If you know how to solve it or have a idea that might work, I would love to hear it.
public class SendAction implements ActionListener {
private JButton sendButton;
private JButton sendButtonServer;
private JTextField text;
private JLabel label;
static ArrayList<String> textList = new ArrayList<String>();
static ArrayList<String> textListServer = new ArrayList<String>();
private String chatText;
public SendAction(JButton sendButton) {
this.sendButton = sendButton;
this.sendButtonServer = sendButtonServer;
}
public SendAction(JTextField text) {
this.text = text;
}
public SendAction(JLabel label) {
this.label = label;
}
public void actionPerformed(ActionEvent e) {
String action = e.getActionCommand();
if (e.getSource() == P2PChatClient.sendButton) {
if (P2PChatClient.text.getText().equals("")) {
} else {
textList.add("Client: " + P2PChatClient.text.getText());
System.out.println("Eingegebene ArrayList Elements: "
+ textList);
chatText = String.join(" | ", textList);
P2PChatClient.label.setText(chatText);
P2PChatClient.text.setText(null);
}
}
if (e.getSource() == P2PChatServer.sendButtonServer) {
if (P2PChatServer.textServer.getText().equals("")) {
} else {
textListServer.add("Server: "
+ P2PChatServer.textServer.getText());
System.out.println("Eingegebene ArrayList Elements: "
+ textListServer);
chatText = String.join(" | ", textListServer);
P2PChatServer.labelServer.setText(chatText);
P2PChatServer.textServer.setText(null);
}
}
}
}
another Class:
public class ChatServerSocket extends Thread {
private int port;
private P2PChatServer serverGUI;
private DataInputStream inStream;
private DataOutputStream outStream;
public ChatServerSocket(int port, P2PChatServer serverGUI) {
this.port = port;
this.serverGUI = serverGUI;
}
public void run() {
ServerSocket server = null;
try {
server = new ServerSocket(port);
} catch (Exception e) {
System.out.println("Fehler: " + e.toString());
}
Socket client;
while (true) {
try {
client = server.accept();
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
inStream = new DataInputStream(in);
outStream = new DataOutputStream(out);
while (true) {
String utf = inStream.readUTF();
// File file = new File(utf);
// if (file.isFile()) {
// file.delete();
// }
SendAction.textListServer.add(utf);
// serverGUI.setMessage(utf);
}
} catch (IOException ioe) {
System.out.println("Server Fehler: " + ioe.toString());
}
}
}
public void sendText(String message) {
// P2PChatServer.send();
try {
if (message != null) {
outStream.writeUTF(message);
}
} catch (IOException ioe) {
System.out.println("Fehler beim senden im Server: "
+ ioe.toString());
} catch (NullPointerException npe) {
System.out.println("Fehler beim senden im Client: "
+ npe.toString());
}
}
}
and another:
public class ChatClientSocket extends Thread {
private String ip;
private int port;
private P2PChatClient client;
private DataInputStream inStream;
private DataOutputStream outStream;
public ChatClientSocket(String ip, int port, P2PChatClient client) {
this.port = port;
this.ip = ip;
this.client = client;
}
public void run() {
try {
Socket clientSocket = new Socket(ip, port);
InputStream in = clientSocket.getInputStream();
OutputStream out = clientSocket.getOutputStream();
inStream = new DataInputStream(in);
outStream = new DataOutputStream(out);
while (true) {
String utf = inStream.readUTF();
SendAction.textList.add(utf);
// client.setMessage(utf);
}
} catch (UnknownHostException uhe) {
System.out.println("Client Fehler: " + uhe.toString());
} catch (IOException ioe) {
System.out.println("Client Fehler: " + ioe.toString());
}
}
public void sendText(String message) {
try {
if (message != null) {
outStream.writeUTF(message);
}
} catch (IOException ioe) {
System.out.println("Fehler beim senden im Client: "
+ ioe.toString());
} catch (NullPointerException npe) {
System.out.println("Fehler beim senden im Client: "
+ npe.toString());
}
}
}
I used a textarea.
With setEditable you cant edit it and scrollArea make it scrollable u know.
textArea.setEditable(false);
scrollArea = new JScrollPane(textArea);
The server accept requests from clients but clients don't get an answer from the server, on the server it accepts client authentication but then the client application shows an error message.
The server and client are on the same LAN.
This is the code of server :
public class UdpServer extends BaseServer {
public static final int UDP_BUFFER = 10 * 1024; // 10Kb
private static final int NUMBER_USER_INFO_REQUEST_RETRIES = 5;
private static final int SECONDS_TO_CHECK_USER_INFO = 15;
DatagramSocket inSocket = null;
DatagramSocket outSocket = null;
BlockingQueue<DatagramPacket> incomingRequests = null;
BlockingQueue<DatagramPacket> outgoingRequests = null;
HandleIncomingPackets handleIncomingPackets = null;
HandleRequests handleRequests = null;
HandleOutgoingPackets handleOutgoingPackets = null;
HandleUserInfoUpdates handleUserInfoUpdates = null;
public UdpServer() throws IOException {
this(4445);
}
public UdpServer(int port) throws IOException {
super();
inSocket = new DatagramSocket(port);
outSocket = new DatagramSocket();
try {
serverUserInfo = new UserInfo(UserInfo.SERVER_USERNAME, inSocket.getLocalAddress().getHostAddress(), inSocket.getLocalPort());
} catch (InvalidDataException e) {
if (DEBUG)
System.out.println("oops... initialising serverUserInfo");
}
incomingRequests = new LinkedBlockingQueue<>();
outgoingRequests = new LinkedBlockingQueue<>();
}
public void run() {
handleIncomingPackets = new HandleIncomingPackets();
handleRequests = new HandleRequests();
handleOutgoingPackets = new HandleOutgoingPackets();
handleUserInfoUpdates = new HandleUserInfoUpdates();
handleIncomingPackets.start();
handleRequests.start();
handleOutgoingPackets.start();
handleUserInfoUpdates.start();
System.out.println("Server Started");
}
private class HandleIncomingPackets extends Thread {
private boolean canRun = true;
private byte[] buf;
private DatagramPacket packet;
#Override
public void run() {
while (canRun) {
buf = new byte[UDP_BUFFER];
packet = new DatagramPacket(buf, buf.length);
try {
inSocket.receive(packet);
} catch (IOException e2) {
if (DEBUG)
System.out.println("ops... receiving a packet from socket");
continue;
}
incomingRequests.add(packet);
}
}
public void stopHandleMessages() {
canRun = false;
}
}
private class HandleOutgoingPackets extends Thread {
private boolean canRun = true;
#Override
public void run() {
while (canRun) {
DatagramPacket dp = null;
try {
dp = outgoingRequests.take();
} catch (InterruptedException e1) { }
if (dp == null)
continue;
try {
outSocket.send(dp);
} catch (IOException e) {
if (DEBUG)
System.out.println("could not send a message: " + dp.toString());
}
}
}
public void stopHandleMessages() {
canRun = false;
}
}
private class HandleRequests extends Thread {
private boolean canRun = true;
#Override
public void run() {
while (canRun) {
DatagramPacket dp = null;
try {
dp = incomingRequests.take();
} catch (InterruptedException e1) { }
if (dp == null)
continue;
String the_msg = new String(dp.getData(), 0, dp.getLength());
the_msg = the_msg.trim();
String message_type = null;
try {
message_type = Procedures.getMessageType(the_msg);
} catch (XmlMessageReprException e) {
if (DEBUG)
System.out.println("Cannot get the message type :( " + e.getMessage());
continue;
}
if (message_type == null) {
if (DEBUG)
System.out.println("message type is null");
continue;
}
if (Procedures.isLoginMessage(message_type)) {
manageLoginRequest(dp);
} else if (Procedures.isRegisterMessage(message_type)) {
manageRegisterRequest(dp);
} else if (Procedures.isLogoutMessage(message_type)) {
manageLogoutRequest(dp);
} else if (Procedures.isUserInfoAnswerMessage(message_type)) {
manageUserInfoAnswer(dp);
}
// do stuff
}
}
public void stopHandleMessages() {
canRun = false;
}
}
private class HandleUserInfoUpdates extends Thread {
boolean canRun = true;
#Override
public void run() {
while (canRun) {
Calendar c = Calendar.getInstance();
Date now = c.getTime();
for (SimpleIMUser simu : registeredUsers) {
// now - last >= Seconds to check
// now >= last + seconds to check
if (!simu.getUser().isOnline())
continue;
c.setTime(simu.last_update);
c.add(Calendar.SECOND, SECONDS_TO_CHECK_USER_INFO * NUMBER_USER_INFO_REQUEST_RETRIES);
if (now.after(c.getTime())) {
simu.getUser().setOffline();
if (DEBUG)
System.out.println("HandlerUserInfoUpdates - set "+ simu.getUser() + " offline...");
continue;
}
c.setTime(simu.last_update);
c.add(Calendar.SECOND, SECONDS_TO_CHECK_USER_INFO);
if (now.after(c.getTime())) {
sendUserInfoRequest(simu);
if (DEBUG)
System.out.println("HandlerUserInfoUpdates - send a userInfoRequest... to: " + simu.getUser());
}
}
try {
Thread.sleep(SECONDS_TO_CHECK_USER_INFO * 1000);
} catch (InterruptedException e) { }
}
}
public void stopHandleMessages() {
canRun = false;
}
}
/*
* various requests/messages managers
*
*/
private void sendUserInfoRequest(SimpleIMUser simu) {
UserInfoRequestMessage uirm = new UserInfoRequestMessage(serverUserInfo);
String uirmXml = null;
try {
uirmXml = uirm.toXML();
} catch (ParserConfigurationException | TransformerException e1) {
//unlikely to be here
}
DatagramPacket p;
try {
p = new DatagramPacket(uirmXml.getBytes(), uirmXml.getBytes().length,
InetAddress.getByName(simu.getUser().getIp()),
simu.getUser().getPort());
} catch (UnknownHostException e) {
/* if there's error... nothing to do */
return;
}
outgoingRequests.add(p);
}
private void manageUserInfoAnswer(DatagramPacket dp) {
String msg = new String(dp.getData(), 0, dp.getLength());
UserInfoAnswerMessage uiam;
try {
uiam = UserInfoAnswerMessage.fromXML(msg);
} catch (XmlMessageReprException e) {
//nothing to do...
return;
}
UserInfo source = uiam.getSource();
SimpleIMUser simu = getTheUserFromRegistered(source);
if (simu == null)
return;
simu.getUser().locationData(source.hasLocationData());
simu.getUser().setAltitude(source.getAltitude());
simu.getUser().setLatitude(source.getLatitude());
simu.getUser().setLongitude(source.getLongitude());
simu.getUser().setIP(source.getIp());
simu.getUser().setPort(source.getPort());
simu.getUser().setOnline();
simu.last_update = Calendar.getInstance().getTime();
}
private void manageLogoutRequest(DatagramPacket dp) {
String request = new String(dp.getData(), 0, dp.getLength());
LogoutMessage lm = null;
try {
lm = LogoutMessage.fromXML(request);
} catch (XmlMessageReprException e) {
return;
}
UserInfo source = lm.getSource();
SimpleIMUser s = getTheUserFromRegistered(source);
if (s == null)
return;
s.getUser().setOffline();
s.last_update = Calendar.getInstance().getTime();
}
private void manageLoginRequest(DatagramPacket packet) {
String request = new String(packet.getData(), 0, packet.getLength());
LoginMessage lm = null;
UserInfo userOfMessage = null;
String password = null;
SimpleIMUser s;
String answer = null;
InetAddress address;
int port;
try {
lm = LoginMessage.fromXML(request);
} catch (XmlMessageReprException e1) {
if (DEBUG)
System.out.println("Login message cannot be serialized :(");
}
userOfMessage = lm.getUser();
password = lm.getPassword();
if (DEBUG)
System.out.println("Login message recieved from \"" + userOfMessage.getUsername() +"\"");
s = getTheUserFromRegistered(userOfMessage);
if (s == null || (s != null && !s.samePassword(password))) {
if (DEBUG)
System.out.println("Sending REFUSE login to \"" + userOfMessage.getUsername() +"\"");
try {
answer = new LoginMessageAnswer(userOfMessage).toXML();
} catch (ParserConfigurationException | TransformerException e) {
if (DEBUG)
System.out.println("ops... should not be here :(");
}
address = packet.getAddress();
port = packet.getPort();
outgoingRequests.add(new DatagramPacket(answer.getBytes(), answer.getBytes().length, address, port));
} else {
if (DEBUG)
System.out.println("Sending ACCEPT login to \"" + userOfMessage.getUsername() +"\"");
address = packet.getAddress();
port = packet.getPort();
s.getUser().locationData(userOfMessage.hasLocationData());
s.getUser().setAltitude(userOfMessage.getAltitude());
s.getUser().setLatitude(userOfMessage.getLatitude());
s.getUser().setLongitude(userOfMessage.getLongitude());
s.getUser().setIP(address.getHostAddress());
s.getUser().setPort(port);
s.getUser().setOnline();
s.last_update = Calendar.getInstance().getTime();
try {
answer = new LoginMessageAnswer(s.getUser(), String.valueOf(s.getUser().hashCode())).toXML();
} catch (ParserConfigurationException | TransformerException e) {
if (DEBUG)
System.out.println("ops... making a loginAnswer message");
}
outgoingRequests.add(new DatagramPacket(answer.getBytes(), answer.getBytes().length, address, port));
ListMessage listMessage = new ListMessage();
fillListMessage(listMessage, s);
try {
answer = listMessage.toXML();
} catch (ParserConfigurationException | TransformerException e) { }
outgoingRequests.add(new DatagramPacket(answer.getBytes(), answer.getBytes().length, address, port));
}
}
private void manageRegisterRequest(DatagramPacket dp) {
String request = new String(dp.getData(), 0, dp.getLength());
RegisterMessage rm = null;
String answer = null;
try {
rm = RegisterMessage.fromXML(request);
} catch (XmlMessageReprException e) {
if (DEBUG)
System.out.println("Register message cannot be serialized :(");
}
if (DEBUG)
System.out.println("Register message recieved from \"" + rm.getUser().getUsername() +"\"");
if (registeredUsers.contains(new SimpleIMUser(rm.getUser(), "DUMMY")) || rm.getUser().equals(serverUserInfo)) {
if (DEBUG)
System.out.println("Sending REFUSE register to \"" + rm.getUser().getUsername() +"\"");
try {
answer = new RegisterMessageAnswer(rm.getUser(), RegisterMessageAnswer.REFUSED).toXML();
} catch (ParserConfigurationException | TransformerException e) {
if (DEBUG)
System.out.println("ops... should not be here :(");
} catch (InvalidDataException e) {
if (DEBUG)
System.out.println("ops... should not be here :(");
}
} else {
if (DEBUG)
System.out.println("Sending ACCEPT register to \"" + rm.getUser().getUsername() +"\"");
rm.getUser().setOffline();
addUserToRegisteredUsers(new SimpleIMUser(rm.getUser(), rm.getPassword()));
try {
answer = new RegisterMessageAnswer(rm.getUser(),RegisterMessageAnswer.ACCEPTED).toXML();
} catch (ParserConfigurationException | TransformerException e) {
if (DEBUG)
System.out.println("ops... should not be here :(");
} catch (InvalidDataException e) {
if (DEBUG)
System.out.println("ops... should not be here :(");
}
}
outgoingRequests.add(new DatagramPacket(answer.getBytes(), answer.getBytes().length, dp.getAddress(), dp.getPort()));
}
#Override
protected void finalize() throws Throwable {
handleUserInfoUpdates.stopHandleMessages();
handleRequests.stopHandleMessages();
handleOutgoingPackets.stopHandleMessages();
handleIncomingPackets.stopHandleMessages();
inSocket.close();
outSocket.close();
super.finalize();
}
}
Anything you could do to help or tell me what I am doing wrong is appreciated.