JProgressBar on button click to show the progress while sending emails - java

I am sending mails with interval from my swing program. I want to show progress bar when button to send emails is clicked. When all emails are sent, progress bar reaches to 100% complete. But progrssbar doesn't show anything while mails are going.
private void btnSendEmailsNowActionPerformed(java.awt.event.ActionEvent evt) {
btnSendEmailsNow.setEnabled(false);
Task task = new Task();
task.start();
//Load property files
loadProps();
//Read config file.
readConfig();
//Take filename "FromEmail_list" after reading config file.
BufferedReader br1=null;
BufferedReader br2=null;
String line1="",line2="";
String csvSplitBy=",";
String strMailFrom="",strPassword="";
String strSendTo="";
int countCSVFrom=0,countCSVSendTo;
System.out.println("strCSVFrom=" + strCSVFrom + ", strcsvSendTo=" + strCSVSendTo);
try{
br1=new BufferedReader(new FileReader(strCSVFrom));
br2=new BufferedReader(new FileReader(strCSVSendTo));
while((line1=br1.readLine())!=null){
countCSVFrom+=1;
String[] strarrFromEmail = line1.split(csvSplitBy);
strMailFrom=strarrFromEmail[0];
strPassword=strarrFromEmail[1];
System.out.println("strFrom="+strMailFrom + ", strPassword="+strPassword);
countCSVSendTo=0;
while((line2=br2.readLine())!=null){
System.out.println("line2="+line2.toString());
countCSVSendTo+=1;
String[] strMailTo=line2.split("\n");
strSendTo=strMailTo[0];
String subject = "Test mail";
String message="";
//inline image
Map<String,String> inlineImage=new HashMap<String,String>();
inlineImage.put("image1", "Logo.jpg");
frmEmailer mailer = new frmEmailer();
String filename=txtHTMLFile.getText();
System.out.println("filename=" + filename);
try{
message=mailer.readHTML(filename,message);
mailer.sendHtmlEmail(strhost, strport, strMailFrom, strPassword, strSendTo,
subject, message,inlineImage);
System.out.println("Email sent successfully.");
Random rand = new Random();
int randomNum = rand.nextInt((8 - 3) + 1) + 3;
System.out.println(randomNum);
Thread.sleep(randomNum*1000); //1000 microseconds = 1 seconds.
if(countCSVSendTo==2){
break;
}
}catch (Exception ex) {
System.out.println("Failed to sent email.");
ex.printStackTrace();
}
}
//System.out.println("countcsvfrom="+countCSVFrom + ", line1=" + line1.toString());
System.out.println("countcsvsendto="+countCSVSendTo);
}
JOptionPane.showMessageDialog(null, "Emails sent successfully!");
btnSendEmailsNow.setEnabled(true);
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
JOptionPane.showMessageDialog(null, "Failed to send Email!");
}catch(IOException ioe ){
JOptionPane.showMessageDialog(null, "Failed to send Email!");
ioe.printStackTrace();
}
}
private class Task extends Thread {
public Task(){
}
public void run(){
for(int i =0; i<= 100; i+=10){
final int progress = i;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
progressbar.setValue(progress);
}
});
try {
Thread.sleep(100);
} catch (InterruptedException e) {}
}
}
}

Try this code :
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt)
{
new Thread(){
public void run(){
btnSendEmailsNow.setEnabled(false);
//Load property files
loadProps();
//Read config file.
readConfig();
//Take filename "FromEmail_list" after reading config file.
BufferedReader br1=null;
BufferedReader br2=null;
String line1="",line2="";
String csvSplitBy=",";
String strMailFrom="",strPassword="";
String strSendTo="";
int countCSVFrom=0,countCSVSendTo;
int EmailCount = 0;
ProgressMonitor pm = new ProgressMonitor(null, "Loading Progress", "Getting Started...", 0, /*number of emails to be sent*/);
System.out.println("strCSVFrom=" + strCSVFrom + ", strcsvSendTo=" + strCSVSendTo);
try{
br1=new BufferedReader(new FileReader(strCSVFrom));
br2=new BufferedReader(new FileReader(strCSVSendTo));
while((line1=br1.readLine())!=null){
countCSVFrom+=1;
String[] strarrFromEmail = line1.split(csvSplitBy);
strMailFrom=strarrFromEmail[0];
strPassword=strarrFromEmail[1];
System.out.println("strFrom="+strMailFrom + ", strPassword="+strPassword);
countCSVSendTo=0;
while((line2=br2.readLine())!=null){
System.out.println("line2="+line2.toString());
countCSVSendTo+=1;
String[] strMailTo=line2.split("\n");
strSendTo=strMailTo[0];
String subject = "Test mail";
String message="";
//inline image
Map<String,String> inlineImage=new HashMap<String,String>();
inlineImage.put("image1", "Logo.jpg");
frmEmailer mailer = new frmEmailer();
String filename=txtHTMLFile.getText();
System.out.println("filename=" + filename);
try{
message=mailer.readHTML(filename,message);
mailer.sendHtmlEmail(strhost, strport, strMailFrom, strPassword, strSendTo,
subject, message,inlineImage);
System.out.println("Email sent successfully.");
EmailCount++;
pm.setProgress(EmailCount);
pm.setNote("Sent " + EmailCount + " Mails.");
Random rand = new Random();
int randomNum = rand.nextInt((8 - 3) + 1) + 3;
System.out.println(randomNum);
Thread.sleep(randomNum*1000); //1000 microseconds = 1 seconds.
if(countCSVSendTo==2){
break;
}
}catch (Exception ex) {
System.out.println("Failed to sent email.");
ex.printStackTrace();
}
}
//System.out.println("countcsvfrom="+countCSVFrom + ", line1=" + line1.toString());
System.out.println("countcsvsendto="+countCSVSendTo);
}
JOptionPane.showMessageDialog(null, "Emails sent successfully!");
btnSendEmailsNow.setEnabled(true);
}catch(FileNotFoundException fnfe){
fnfe.printStackTrace();
JOptionPane.showMessageDialog(null, "Failed to send Email!");
}catch(IOException ioe ){
JOptionPane.showMessageDialog(null, "Failed to send Email!");
ioe.printStackTrace();
}
}
}.start();
}
You can easily do that thing with ProgressMonitor

Related

Multi Threads Socket Java

My client:
class Read_ChatClient extends Thread{
private static Socket client;
private String user;
static ArrayList<SingleChatF> chatFrames = new ArrayList<>();
public Read_ChatClient(Socket client, String username) {
this.client = client;
this.user = username;
}
public void checkAddNewFrame(String sourceName, String desName, String mess){
boolean exitFrame = false;
int index = 0;
for(SingleChatF frame: chatFrames) {
System.out.println(index + "; " + frame.getSourceName() + "; " + frame.getDestName());
if (frame.Match(sourceName, desName)) {
frame.gettxtchatall().append(mess + "\n");
System.out.println("Founded frame: " + sourceName + "; " + desName);
exitFrame = true;
break;
};
index++;
}
if(!exitFrame) {
SingleChatF newFrame = new SingleChatF(this.client, sourceName, desName);
newFrame.setVisible(true);
newFrame.gettxtchatall().append(mess + "\n");
chatFrames.add(newFrame);
System.out.println("Created new frame: " + sourceName + "; " + desName);
}
}
#Override
public void run(){
System.out.println(new Date().getTime() + " - Read_ChatClient");
DataInputStream dis = null;
try {
dis = new DataInputStream(client.getInputStream());
System.out.println(" - Read_ChatClient client.getInputStream() OK");
while(true) {
System.out.println(" - Read_ChatClient......");
String sms = dis.readUTF();
System.out.println(" - Read_ChatClient.sms: "+sms);
if (sms.contains("login_successed")){
System.out.println(" - Read_ChatClient: Join()");
String[] info = sms.split(";");
String username = info[1];
String[] onlineuserList = info[2].split(",");
if (username.equalsIgnoreCase(user)) {
MultiThreads_LoginClient.setLoginF(false);
MultiThreads_LoginClient.chatFrame = new ChatF(user, client);
MultiThreads_LoginClient.chatFrame.setVisible(true);
JTable OnlineTab = MultiThreads_LoginClient.chatFrame.getjtableonlineuser();
DefaultTableModel model = (DefaultTableModel) OnlineTab.getModel();
for (String name : onlineuserList) {
model.addRow(new String[]{name});
}
}else if(!username.equalsIgnoreCase(user)){
MultiThreads_LoginClient.chatFrame.getjtableonlineuser().setModel(new DefaultTableModel(null,new String[]{"Online Users"}));
for (String name : onlineuserList) {
JTable OnlineTab = MultiThreads_LoginClient.chatFrame.getjtableonlineuser();
DefaultTableModel model = (DefaultTableModel) OnlineTab.getModel();
model.addRow(new String[]{name});
}
MultiThreads_LoginClient.chatFrame.gettxtchatall().append(username+" da ket noi\n");
}
} else if (sms.contains("login_failed;")) {
JOptionPane.showMessageDialog(null, "Login Failed");
} else if (sms.contains("user_actived")) {
JOptionPane.showMessageDialog(null, "User's activing");
}else if(sms.contains("updateOnlineUserList")){
String[] list = sms.split(":");
String[] newList = list[1].split(",");
MultiThreads_LoginClient.chatFrame.getjtableonlineuser().setModel(new DefaultTableModel(null,new String[]{"Online Users"}));
for (String name : newList) {
JTable OnlineTab = MultiThreads_LoginClient.chatFrame.getjtableonlineuser();
DefaultTableModel model = (DefaultTableModel) OnlineTab.getModel();
model.addRow(new String[]{name});
}
System.out.println("updateOnlineUserList:"+sms);
}else if(sms.contains("chatPrivate")){
//{ChatPrivate}:{Source_name}:{des_name}:{mess}:{host:port}
System.out.println("ClientRead_chatPrivate: " + sms);
String[] content = sms.split(";");
String sourceName = content[1];
String desName = content[2];
String mess = content[3];
checkAddNewFrame(desName, sourceName, mess);
}else if(sms.contains("AlertAlert_SendFilesToClient")){
System.out.println("AlertAlert_SendFilesToClient");
currentThread().wait();
Read_FileClient rf = new Read_FileClient(client);
rf.start();
}else{
MultiThreads_LoginClient.chatFrame.gettxtchatall().append("\n" + sms);
System.out.println(sms);
}
}
} catch (Exception e) {
try {
currentThread().wait();
Read_FileClient rf = new Read_FileClient(client);
rf.start();
//dis.close();
} catch (InterruptedException ex) {
Logger.getLogger(Read_ChatClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
}}
My Server:
class Read_ChatServer extends Thread{
private static Socket socket;
private static SingleChatFrame_SV singlechatFrame;
public static void setsocket(Socket socket){
Read_ChatServer.socket = socket;
}
public Read_ChatServer(Socket client) {
this.socket = client;
}
#Override
public void run(){
System.out.println("Read_ChatServer");
DataInputStream dis = null;
DataOutputStream dos = null;
try {
System.out.println("Checking socket.getInputStream()");
dis = new DataInputStream(socket.getInputStream());
System.out.println("OK socket.getInputStream()");
while (true) {
String sms = dis.readUTF();
System.out.println(" - Read_ChatServer: " + sms);
if (sms.contains("Login_Requiere")) {
//{Login_Requiere};{username};{password}
try {
dis = new DataInputStream(socket.getInputStream());
dos = new DataOutputStream(socket.getOutputStream());
System.out.println("Trying login for user " + sms);
String[] contents = sms.split(";");
String info[] = sms.split(";");//info[1]: username - info[2]:pass
Connection con = DBConnection.getConnection();
String query = "Select *from `info` where `user`=? AND `pw`=?";
PreparedStatement pst;
ResultSet rs;
try {
pst = con.prepareStatement(query);
pst.setString(1, info[1]);
pst.setString(2, info[2]);
rs = pst.executeQuery();
if (rs.next()) {
// login;{success: true, onlineuser: ["", ""]}
// chat;
if (!MultiThreads_LoginServer.checkuserexits(info[1])) {
accountinfo temp = new accountinfo(socket, info[1]);
MultiThreads_LoginServer.chatFrame_Server.gettxtchatall().append("Da ket noi " + info[1] + "\n");
System.out.println("Da ket noi " + socket);
MultiThreads_LoginServer.accountinfoList.add(temp);
showonlineuser();
String statusString = "login_successed;" + info[1] + ";" + MultiThreads_LoginServer.convertoString();
BroadCastUserListToAllClients wu = new BroadCastUserListToAllClients(statusString);
wu.start();
} else {
dos.writeUTF("user_actived; ; ");
}
} else {
dos.writeUTF("login_failed; ; ");
//dos.flush();
}
} catch (SQLException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
DBConnection.closeConnection(con);
MultiThreads_LoginServer.chatFrame_Server.gettxtchatall().append("User: " + info[1] + "\tPass: " + info[2] + "\n");
} catch (Exception e) {
System.out.println(" - Error Read_LoginServer: " + e.getMessage());
try {
dis.close();
dos.close();
socket.close();
} catch (IOException ex) {
Logger.getLogger(Read_LoginServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}else if (sms.contains("exit")) {
String[] exitInfo = sms.split(":");
String notify = "Ngat ket noi voi : " + exitInfo[1]+"\n";
try {
MultiThreads_LoginServer.remove_user(exitInfo[1]);
if (MultiThreads_LoginServer.accountinfoList.isEmpty()) {
MultiThreads_LoginServer.chatFrame_Server.gettxtchatall().append("No User Online!");
} else {
showonlineuser();
MultiThreads_LoginServer.chatFrame_Server.gettxtchatall().append(notify + "\n");
System.out.println(" - Read_ChatServer: " + notify);
for (accountinfo item : MultiThreads_LoginServer.accountinfoList) {
dos = new DataOutputStream(item.socket.getOutputStream());
dos.writeUTF(notify);
//dos.flush();
}
}
String currentList = convertoString();
BroadCastUserListToAllClients broad = new BroadCastUserListToAllClients("updateOnlineUserList: " + currentList);
broad.start();
} catch (Exception e) {
showonlineuser();
MultiThreads_LoginServer.chatFrame_Server.gettxtchatall().append(notify + "\n");
MultiThreads_LoginServer.chatFrame_Server.gettxtchatall().append("No User Online!");
}
} else if(sms.contains("chatPrivate")){
System.out.println("server_chatPrivate: "+ sms);
//{ChatPrivate};{Source_name};{des_name};{mess}
String[] content = sms.split(";");
String s_name = content[1];
String d_name = content[2];
if(d_name.equalsIgnoreCase("Server")){
//
}else{
for(accountinfo item:MultiThreads_LoginServer.accountinfoList){
if(item.username.equalsIgnoreCase(d_name)){
dos = new DataOutputStream(item.socket.getOutputStream());
dos.writeUTF(sms);
}
}
}
}else if(sms.contains("Alert_SendFiles")){
System.out.println("Alert_SendFiles");
String[] content = sms.split(":");
String des_name = content[1];
AlertAlert_SendFilesToClient alert = new AlertAlert_SendFilesToClient(des_name);
alert.start();
Thread.sleep(1000);
System.out.println("-Alert_SendFiles: pass alert");
currentThread().wait();
Read_FileServer rf = new Read_FileServer(socket);
rf.start();
}else{
MultiThreads_LoginServer.chatFrame_Server.gettxtchatall().append(sms + "\n");
for (accountinfo item : MultiThreads_LoginServer.accountinfoList) {
dos = new DataOutputStream(item.socket.getOutputStream());
dos.writeUTF(sms);
//dos.flush();
}
}
}
} catch (Exception e) {
System.out.println("No user online!");
System.out.println(" - Error Read_ChatServer: " + e.getMessage());
try {
dis.close();
//dos.close();
} catch (IOException ex) {
System.out.println(" - Error Read_ChatServer: " + ex.getMessage());
Logger.getLogger(Read_ChatServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}}
My class Send file:
class Write_SendFiles extends Thread{
private Data_file data;
private Socket client;
public Write_SendFiles(Data_file data,Socket client) {
this.data = data;
this.client = client;
}
#Override
public void run() {
System.out.println("Write_SendFiles");
ObjectOutputStream oos = null;
try {
oos = new ObjectOutputStream(client.getOutputStream());
System.out.println("-Write_SendFiles:"+data.getfilename());
oos.writeObject(data);
System.out.println("-Write_SendFiles: pass send file");
} catch (IOException ex) {
/*try {
oos.close();
} catch (IOException ex1) {
System.out.println("-Write_SendFiles Err:"+ex.getMessage());
Logger.getLogger(Write_SendFiles.class.getName()).log(Level.SEVERE, null, ex1);
}*/
System.out.println("-Write_SendFiles Err:"+ex.getMessage());
Logger.getLogger(Write_SendFiles.class.getName()).log(Level.SEVERE, null, ex);
}
} }
class Read_FileClient extends Thread{
private Socket client;
public Read_FileClient(Socket client) {
this.client = client;
}
#Override
public void run() {
System.out.println("Client file");
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(client.getInputStream());
System.out.println("-Server file: pass new obj");
try {
Data_file datafile = (Data_file) ois.readObject();
System.out.println("-Server file:read file successfully");
boolean exitingChatFrame_file = false;
for (SingleChatF single : Read_ChatClient.chatFrames) {
exitingChatFrame_file = single.Match(datafile.getdes_name(), datafile.getdes_name());
System.out.println("File - Finding frame: Source=" + datafile.getdes_name() + "; Dest=" + datafile.getdes_name() + "; " + exitingChatFrame_file);
if (exitingChatFrame_file) {
JList FilesTranfer = single.getjlisttranfer();
DefaultListModel model = new DefaultListModel();
FilesTranfer.setModel(model);
model.addElement(datafile);
System.out.println("Founded");
single.gettxtchatall().append("Getting file...");
break;
}
}
if (!exitingChatFrame_file) {
System.out.println("ClientRead_chatPrivate: not active");
SingleChatF newFrame = new SingleChatF(this.client, datafile.getdes_name(), datafile.getdes_name());
newFrame.setVisible(true);
JList FilesTranfer = newFrame.getjlisttranfer();
DefaultListModel model = new DefaultListModel();
FilesTranfer.setModel(model);
model.addElement(datafile);
chatFrames.add(newFrame);
newFrame.gettxtchatall().append("Getting file...");
}
//client.close();
} catch (ClassNotFoundException ex) {
Logger.getLogger(Read_ChatClient.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (IOException ex) {
Logger.getLogger(Read_FileClient.class.getName()).log(Level.SEVERE, null, ex);
}
}}
My Server read file:
class Read_FileServer extends Thread{
private Socket client;
public Read_FileServer(Socket client) {
this.client = client;
}
#Override
public void run() {
System.out.println("Server Read_FileServer");
ObjectInputStream ois = null;
ObjectOutputStream oos = null;
try {
ois = new ObjectInputStream(client.getInputStream());
try {
Data_file datafile = (Data_file)ois.readObject();
System.out.println("-Server Read_FileServer: read file successfully");
for(accountinfo item : MultiThreads_LoginServer.accountinfoList){
if(item.username.equalsIgnoreCase(datafile.getdes_name())){
oos = new ObjectOutputStream(item.socket.getOutputStream());
oos.writeObject(datafile);
}
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(Read_FileServer.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (IOException ex) {
try {
ois.close();
oos.close();
} catch (IOException ex1) {
Logger.getLogger(Read_FileServer.class.getName()).log(Level.SEVERE, null, ex1);
}
Logger.getLogger(Read_FileServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
But now i have the function is send file. So i have to use ObjectInputStream and Object OutputStream .The problems is 2 type difference between DataInputStream,DataOutputStream and ObjectInputStream,OutputStream.How can i put thread of ObjectInputStream and ObjectOutputStreadm to my class. thanks you!
try (DataInputStream dis = new DataInputStream(socket.getInputStream());
DataOutputStreamdos = new DataOutputStream(socket.getOutputStream())){
System.out.println("Trying login for user " + sms);
String[] contents = sms.split(";");
String info[] = sms.split(";");//info[1]: username - info[2]:pass
Connection con = DBConnection.getConnection();
String query = "Select *from `info` where `user`=? AND `pw`=?";
PreparedStatement pst;
ResultSet rs;
try {
pst = con.prepareStatement(query);
pst.setString(1, info[1]);
pst.setString(2, info[2]);
rs = pst.executeQuery();
if (rs.next()) {
// login;{success: true, onlineuser: ["", ""]}
// chat;
if (!MultiThreads_LoginServer.checkuserexits(info[1])) {
accountinfo temp = new accountinfo(socket, info[1]);
MultiThreads_LoginServer.chatFrame_Server.gettxtchatall().append("Da ket noi " + info[1] + "\n");
System.out.println("Da ket noi " + socket);
MultiThreads_LoginServer.accountinfoList.add(temp);
showonlineuser();
String statusString = "login_successed;" + info[1] + ";" + MultiThreads_LoginServer.convertoString();
BroadCastUserListToAllClients wu = new BroadCastUserListToAllClients(statusString);
wu.start();
} else {
dos.writeUTF("user_actived; ; ");
}
} else {
dos.writeUTF("login_failed; ; ");
//dos.flush();
}
} catch (SQLException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
DBConnection.closeConnection(con);
MultiThreads_LoginServer.chatFrame_Server.gettxtchatall().append("User: " + info[1] + "\tPass: " + info[2] + "\n");
} catch (Exception e) {
System.out.println(" - Error Read_LoginServer: " + e.getMessage());
}

Client/Server Chat app with file transfer JAVA Sockets

I am new to java and I made a chat application through which client and server can send and receive messages, now I was trying to send a file from client to server but after the file is received by server , client and server both cant send messages , Here is the code :
Client Side :
import java.io.*;
import java.net.*;
import javax.swing.JFileChooser;
public class ClientFrame extends javax.swing.JFrame {
static Socket s;
static DataOutputStream dos1;
static DataInputStream dis;
static javax.swing.JTextArea jT;
static JFileChooser fc = new JFileChooser();
File file;
public ClientFrame() {
initComponents();
jT = jTextArea1;
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//send message
try {
String str1 = jTextField1.getText();
String o = jT.getText() + "\n" + " Client ->" + str1;
jT.setText(o);
dos1.writeUTF(str1);
} catch (Exception ex) {
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
//open file chooser
fc.showOpenDialog(this);
file = fc.getSelectedFile();
jTextField3.setText(file.getAbsolutePath());
}
private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
//send file
try {
String st = jT.getText() + "\n" + " Client -> " + "Sending a file";
jT.setText(st);
String str1 = "Client Sending a file,Press 'REC File' ";
String st1 = "\n" + " Client ->" + str1;
dos1.writeUTF(st1);
} catch (Exception e) {
}
long length = file.length();
byte[] bytes = new byte[65536];//65536 is max, i think
InputStream in;
try {
in = new FileInputStream(file);
OutputStream out = s.getOutputStream();
int count;
while ((count = in.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.close();
in.close();
s_r_m();
} catch (Exception ex) {
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ClientFrame().setVisible(true);
}
});
try {
s = new Socket("localhost", 3000);
} catch (Exception e) {
}
s_r_m();
}
public static void s_r_m() {
System.out.println("call srm");
try {
dis = new DataInputStream(s.getInputStream());
dos1 = new DataOutputStream(s.getOutputStream());
while (true) {
String str = (String) dis.readUTF();
String out = jT.getText() + "\n" + " Server ->" + str;
jT.setText(out);
}
} catch (Exception ex) {
}
}
}
Server Side :
import java.io.*;
import java.net.*;
import javax.swing.JFileChooser;
public class ServerFrame extends javax.swing.JFrame {
static ServerSocket ss;
static Socket s;
static DataInputStream dis;
static DataOutputStream dos1;
static javax.swing.JTextArea jT;
static JFileChooser fc = new JFileChooser();
File file;
public ServerFrame() {
initComponents();
jT = jTextArea1;
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
//send message
try {
String str1 = jTextField1.getText();
String out = jT.getText() + "\n" + " Server ->" + str1;
jT.setText(out);
dos1.writeUTF(str1);
} catch (Exception ex) {
}
}
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
//open file chooser
fc.showOpenDialog(this);
file = fc.getSelectedFile();
jTextField3.setText(file.getAbsolutePath());
}
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
//rec file
InputStream in = null;
OutputStream out = null;
try {
in = s.getInputStream();
out = new FileOutputStream("F:\\yoMama.exe");
int count;
byte[] buffer = new byte[65536];
while ((count = in.read(buffer)) > 0) {
out.write(buffer, 0, count);
}
String o = jT.getText() + "\n" + " Client ->" + " File received";
jT.setText(o);
out.close();
in.close();
s_r_m();
} catch (Exception ex) {
}
}
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ServerFrame().setVisible(true);
}
});
try {
ss = new ServerSocket(3000);
s = ss.accept();//will accept connection from client,waiting state untill client connects
s_r_m();
} catch (Exception e) {
}
}
public static void s_r_m() {
System.out.println("call srm");
try {
dis = new DataInputStream(s.getInputStream());
dos1 = new DataOutputStream(s.getOutputStream());
while (true) {
String str = dis.readUTF();
String out = jT.getText() + "\n" + " Client ->" + str;
jT.setText(out);
}
} catch (Exception ex) {
}
}
}
The problem is in the s_r_m() function. In while loop first statement is String str = dis.readUTF(); So here both Client and Server will wait for the reply from the other side first which will end up in a Deadlock. So Any of them won't be able to send any data till the receive from the other side.
So there you need to change code accordingly. I have implemented a code to solve this problem which takes input from Key-Board(STDIN).
DataInputStream dis=new DataInputStream(sckt.getInputStream());
DataInputStream dis1=new DataInputStream(System.in);
DataOutputStream dos=new DataOutputStream(sckt.getOutputStream());
String str="";
while(true)
{
while(dis.available()>0) //If input is available from the other side.
{
String out = jT.getText() + "\n" + " Client ->" + dis.readUTF();
jT.setText(out);
}
while(dis1.available()>0) //If input is available from STDIN to send it to the other side.
{
str=sc.nextLine();
dos.writeUTF(str);
dos.flush();
}
}
Here you can change code of taking input from STDIN to Text-Field you have in your application. So Whenever a user press Send Button , It will send the message to the other side.

SocketTimeoutException in android when trying video streaming

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.

Socket not sending to Client or Client not recieving

I have a Server class and a Client class which is run on an android device. Basically, I need to load the user's friends and their IP address. The user's friends are stored in an ArrayList. So the client must send the friend's name and the server will respond with an IP address if the friend is online or a "-1" if the friend is offline. The server has access to all the users and stores it in an Arraylist of my defined type. My problem is that the client doesn't receive the IP Address/"-1" from the server, so only one friend is checked as the server is waiting for a response. The Login of Client is done elsewhere and is working perfectly.
Server:
public class Server {
private static final int port = 9001;
private static final String IPAddr = "xxx.xxx.xx.10";
ServerSocket server = null;
ArrayList <Client> users = new ArrayList<Client>();
public Server(){
readUsers();
try{
server = new ServerSocket(port);
System.out.println("connected server on port" + port);
while(true){
System.out.println("waiting for connection my ip add is "+ InetAddress.getLocalHost().getHostAddress());
Socket clientsocket = server.accept();
System.out.println("Connect to client:"+ clientsocket.getInetAddress().getHostName());
ClientThread client = new ClientThread(clientsocket);
client.start();
}
} catch(IOException e) {
System.err.println("Could not listen on port");
}
}
public void readUsers() {
//read form user text file on start up
ReadFile reader = new ReadFile("users.txt");
try{
String[] data = reader.OpenFile();
for (int i = 0 ; i<data.length; i++){
String[] parts = data[i].split(" ");
ArrayList<String> ips = new ArrayList<String>();
for(int j =2; j<parts.length; j++){
ips.add(parts[j]);
}
Client clnt = new Client(parts[0],parts[1], ips);
users.add(clnt);
}
}catch(Exception e){
System.err.println("Couldn't read in data");
}
}
public void RegisterUser(){
//append to user text if a new user registers
}
//Thread
public class ClientThread extends Thread {
private Socket sckt = null;
private String purpose;
ObjectOutputStream objectOutput;
ObjectInputStream objectInput;
public ClientThread(Socket sckt){
super("ClientThread");
this.sckt = sckt;
}
public void run(){
try{
objectOutput = new ObjectOutputStream(sckt.getOutputStream());
objectOutput.flush();
objectInput = new ObjectInputStream(sckt.getInputStream());
purpose = objectInput.readUTF();
if(purpose.contains("login")){
LoginUser();
}else {
LoadClientIP();
}
} catch(Exception e){
System.err.println("Couldnt read purpose: "+ purpose);
}
}
public void LoginUser(){
try{
String Username = objectInput.readUTF();
String Password = objectInput.readUTF();
int ClientIndex = isClient(Username);
if (ClientIndex != -1){
if(users.get(ClientIndex).password.equals(Password)){
//password correct -> send friends
users.get(ClientIndex).online = true;
users.get(ClientIndex).SetCurrentIP(sckt.getRemoteSocketAddress().toString());
objectOutput.writeUTF("correct");
System.out.println(Username + " is correct");
LoadClientFriends(Username, ClientIndex);
objectOutput.writeObject(users.get(ClientIndex).Friends);
System.out.println("Friends sent");
} else {
//password incorrect -> retry
objectOutput.writeUnshared("password");
System.out.println(Username + " has wrong password");
}
} else {
//not a registered client
objectOutput.writeUTF("wrong");
System.out.println(Username + " is not a client");
}
} catch(Exception e){
System.err.println("Couldnt connect to Client socket");
}
}
public void LoadClientIP(){
try{
int size = Integer.parseInt(objectInput.readUTF()); //keep track of the number of friends
System.out.println("The size of friends:"+ size);
for (int j =0; j<size; j++){
String client = objectInput.readUTF();
System.out.println("Client: "+ client);
int i = isClient(client); //index of friend is user arraylist
if (users.get(i).online == true){
String IP_add = users.get(i).IP.get(users.get(i).CurrentIP);
objectOutput.writeUTF(IP_add);
System.out.println("Client is at index i "+ i + " with IP "+ IP_add);
}else {
objectOutput.writeUTF("-1");
System.out.println("Client is not online");
}
}
System.out.println("out of while");
}catch (Exception e){
System.err.println("Couldn't load IP");
}
}
}
public void LoadClientFriends(String name, int index){
//upon a client signing in, server must load his friends contacts
ReadFile reader = new ReadFile(name+".txt");
try{
String[] data = reader.OpenFile();
for (int i = 0 ; i<data.length; i++){
users.get(index).Friends.add(data[i]);
}
}catch(Exception e){
System.err.println("Couldn't read in friend data");
}
}
public int isClient(String name){
boolean isclient = false;
int i =0;
int index =-1;
while((isclient == false) && (i<users.size())){
if (name.equals(users.get(i).Username)){
isclient = true;
index = i;
}else {
i++;
}
}
return index;
}
public static void main(String[] args){
Server svr = new Server();
}
}
Client/Android:
public class chat_screen extends ActionBarActivity {
ArrayList<String> friends;
ArrayList<String> onlineIP;
ArrayList<String> onlineFriend;
private static final int port = 9001;
private static final String IPAddr = "xx.x.x.4";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_menu);
friends = (ArrayList<String>) getIntent().getSerializableExtra("Friends");
Thread FriendThread = new Thread(Connect);
FriendThread.start();
}
//Thread
Runnable Connect = new Runnable()
{
public void run()
{
try {
//Problems: getting stuck when reading in friends, only is able to send the first friend
Socket connection = new Socket(IPAddr,port);
ObjectOutputStream objectout = new ObjectOutputStream(connection.getOutputStream());
objectout.flush();
ObjectInputStream objectin = new ObjectInputStream(connection.getInputStream());
//send purpose
objectout.writeUTF("load");
objectout.flush();
objectout.writeUTF(Integer.toString(friends.size()));
objectout.flush();
//send friends name to get IP
for(int i =0; i<friends.size(); i++){
objectout.writeUTF(friends.get(i));
objectout.flush();
String ip = objectin.readUTF(); //stuck on this line
if ((ip.contains("-1"))== false){
onlineIP.add(ip);
onlineFriend.add(friends.get(i));
}else {
//do nothing
}
}
connection.close();
}catch (Exception e){
finish();
}
}
};
}

Sending image Through TCP Socket in Java

I'm trying to make a Client Server Application which the server list name of available images and the client select one of them to download Such as here :
Thread in Server
public void run()
{
try {
in = new DataInputStream (server.getInputStream());
out = new DataOutputStream(server.getOutputStream());
out.writeUTF("To List images write list");
out.writeUTF("To Exit write 2");
out.flush();
while((line = in.readUTF()) != null && !line.equals("2")) {
if(line.equalsIgnoreCase("list"))
{
String [] images= processor.listImages();
for ( int i=0;i<images.length;i++) {
out.writeUTF((+1)+"-"+images[i]);
out.flush();
line = "";
}
out.writeUTF("-1");
line = in.readUTF();
if(line.equalsIgnoreCase("2"))
{
break;
}else
{
BufferedImage img =processor.processInput(line);
boolean cc = ImageIO.write(img,"JPG",server.getOutputStream());
if(!cc)
{
out.writeUTF("The entered image is not avaliable !");
}else
{
System.out.println("Image Sent");
}
}
}else if(line.equalsIgnoreCase("2")){
break;
}
}
try{
in.close();
out.close();
server.close();
}catch(Exception e){
System.out.println("Error : "+ e.getMessage());
}
} catch (IOException e) {
System.out.println("IOException on socket listen: " + e.getMessage());
}
}
Client :
public void start() throws IOException
{
String line="";
while(true)
{
try{
line = inputFromStream.readUTF();
System.out.println(line);
line = inputFromStream.readUTF();
System.out.println(line);
line = readFromConsol.readLine();
writeToStream.writeUTF(line);
if(line.equalsIgnoreCase("2")){
break;
}else if(line.equalsIgnoreCase("list")){
boolean check=true;
while(check){
line = inputFromStream.readUTF();
System.out.println(line);
if("-1".equals(line)) {
check=false;
}
}
line = readFromConsol.readLine();
if(line.equalsIgnoreCase("2")) {
break;
}else
{
writeToStream.writeUTF(line);
BufferedImage img=ImageIO.read(
ImageIO.createImageInputStream(client.getInputStream()));
File f = new File("E:/MyFile.png");
f.createNewFile();
ImageIO.write(img, "PNG", f);
//process.saveImage(tmp);
System.out.println("Saved");
}
}
}catch(Exception e)
{
System.out.println(e);
break;
}
}
try{
inputFromStream.close();
readFromConsol.close();
writeToStream.close();
this.client.close();
}catch(Exception e){
System.out.println("Error : "+e.getMessage());
}
}
The problem is that all commands are successfully submitted till image receiving image stop there doesn't move
Try doing a flush of the outstream on the sending socket, then close the socket.
The problem appears to be that until the socket is flushed and closed the receiving IOImage.read() will wait thinking there are more images in the stream.

Categories