Windows impliementation of simple chat program

import java.io.*;
import java.net.*;
import java.util.Scanner;
public class TCPClient {
   public static void main(String args[]) throws Exception {
     String fromServer;
     String toClient;
     Scanner scanner = new Scanner(System.in);
     BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
     Socket clientSocket = new Socket("plato", 5454); //Port number
     DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
     BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
     System.out.println("<---Connection Established, type 'QUIT' to end this conversation.--->");
     //A message notifying both users about the connection.
     while (true) {
       fromServer = inFromServer.readLine(); //Read message from server.
       System.out.println(fromServer); //Print out the message from the server.
       System.out.println("Enter a message:"); //Server prompts to type a message to Client.
       toClient = scanner.nextLine(); //The message gets read through the Scanner.
       if (toClient.equals("QUIT")) {
         System.out.println("Chat Terminated"); //A message showing that the conversation has ended.
         System.exit(0); //Then the Client closes the conversation.
       } else {
         outToServer.writeBytes("FROM CLIENT: " + toClient + '\n'); //Send the message to Server.
import java.io.*;
import java.net.*;
import java.util.Scanner;
public class TCPServer {
   public static void main(String args[]) throws Exception {
     String fromClient;
      String fromServer;
      Scanner scanner = new Scanner(System.in);
      ServerSocket welcomeSocket = new ServerSocket(5454); //Port Number
      Socket connectionSocket = welcomeSocket.accept();
      BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
      DataOutputStream toClient = new DataOutputStream(connectionSocket.getOutputStream());
      System.out.println("<---Connection Established--->"); //A message notifying both users about the connection.
      while (true) { //An infinite loop letting the conversation go on until Client types in "QUIT".
        System.out.println("Enter a message:"); //Client prompts to type a message to Server.
        fromServer = scanner.nextLine(); //The message gets read through the Scanner.
        toClient.writeBytes("FROM SERVER: " + fromServer + '\n'); //It then sends it to the Client.
        fromClient = inFromClient.readLine(); //Read message from the Client.
        System.out.println(fromClient); //Print out the message from the Client.
}What do I need to change in order get this to work with windows command prompt cos I have no idea myself. Bare in mind also that I'll be using this at home to test stuff. It work at uni with unix but department is closed for the holidays.
Thanks

Thanks
I've got another question
import java.io.*;
import java.net.*;
import java.util.Scanner;
import java.math.*;
public class TCPServer {
   public static void main(String args[]) throws Exception {
     String fromClient;
      String fromServer;
      Scanner scanner = new Scanner(System.in);
      ServerSocket welcomeSocket = new ServerSocket(80); //Port Number
      Socket connectionSocket = welcomeSocket.accept();
      BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
      DataOutputStream toClient = new DataOutputStream(connectionSocket.getOutputStream());
      System.out.println("<---Connection Established--->"); //A message notifying both users about the connection.
      BigInteger b1 = new BigInteger("41241");
      BigInteger b2 = new BigInteger("29592");
      BigInteger b3 = new BigInteger("69311");
      byte [] a = null;
      a = b1.toByteArray();
      byte [] b = null;
      b = b2.toByteArray();
      byte [] c = null;
      c = b3.toByteArray();
      toClient.write(a, 0, a.length);
      toClient.flush();
      toClient.write(b, 0, b.length);
      toClient.flush();
      toClient.write(c, 0, c.length);
      toClient.flush();
      while (true) { //An infinite loop letting the conversation go on until Client types in "QUIT".
        System.out.println("Enter a message:"); //Client prompts to type a message to Server.
        fromServer = scanner.nextLine(); //The message gets read through the Scanner.
        toClient.writeBytes("FROM SERVER: " + fromServer + '\n'); //It then sends it to the Client.
        fromClient = inFromClient.readLine(); //Read message from the Client.
        System.out.println(fromClient); //Print out the message from the Client.
}Currently I'm sending 3 BigInt numbers in the form of a Byte array.
When I run the TCPServer then the TCPClient, the first message I type from the server side displays some weird looking characters. Im guessing these are the numbers but how can I from the TCPClient side extract these weird looking characters as BigInts and store them (which I can do in a BigInt array or something).
Thanks

Similar Messages

  • Simple chat program

    Hi! I would like to implement a simple chat program for iphone (i know that many others still exist). My doubt is about the chat window. I need something like a view or a tableCell to add at the window every time i recieve or write a message, and the view where the conversation happens need to be "slidable"...how can i do this thing? Any suggestion?

    There is no standard control that will help you do this. You will most likely want to implement a custom UIScrollView. Within that you will place custom controls programatically to render the conversation or just manage the offsets yourself and draw the text and graphics by overriding the drawRect method.

  • Need Help with Simple Chat Program

    Hello Guys,
    I'm fairly new to Java and I have a quick question regarding a simple chat program in java. My problem is that I have a simple chat program that runs from its own JFrame etc. Most of you are probably familiar with the code below, i got it from one of my java books. In any case, what I'm attempting to do is integrate this chat pane into a gui that i have created. I attempted to call an instace of the Client class from my gui program so that I can use the textfield and textarea contained in my app, but it will not allow me to do it. Would I need to integrate this code into the code for my Gui class. I have a simple program that contains chat and a game. The code for the Client is listed below.
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import javax.swing.*;
    public class Client
    extends JPanel {
    public static void main(String[] args) throws IOException {
    String name = args[0];
    String host = args[1];
    int port = Integer.parseInt(args[2]);
    final Socket s = new Socket(host, port);
    final Client c = new Client(name, s);
    JFrame f = new JFrame("Client : " + name);
    f.addWindowListener(new WindowAdapter() {
    public void windowClosing(WindowEvent we) {
    c.shutDown();
    System.exit(0);
    f.setSize(300, 300);
    f.setLocation(100, 100);
    f.setContentPane(c);
    f.setVisible(true);
    private String mName;
    private JTextArea mOutputArea;
    private JTextField mInputField;
    private PrintWriter mOut;
    public Client(final String name, Socket s)
    throws IOException {
    mName = name;
    createUI();
    wireNetwork(s);
    wireEvents();
    public void shutDown() {
    mOut.println("");
    mOut.close();
    protected void createUI() {
    setLayout(new BorderLayout());
    mOutputArea = new JTextArea();
    mOutputArea.setLineWrap(true);
    mOutputArea.setEditable(false);
    add(new JScrollPane(mOutputArea), BorderLayout.CENTER);
    mInputField = new JTextField(20);
    JPanel controls = new JPanel();
    controls.add(mInputField);
    add(controls, BorderLayout.SOUTH);
    mInputField.requestFocus();
    protected void wireNetwork(Socket s) throws IOException {
    mOut = new PrintWriter(s.getOutputStream(), true);
    final String eol = System.getProperty("line.separator");
    new Listener(s.getInputStream()) {
    public void processLine(String line) {
    mOutputArea.append(line + eol);
    mOutputArea.setCaretPosition(
    mOutputArea.getDocument().getLength());
    protected void wireEvents() {
    mInputField.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
    String line = mInputField.getText();
    if (line.length() == 0) return;
    mOut.println(mName + " : " + line);
    mInputField.setText("");

    Thanks for ur help!i have moved BufferedReader outside the loop. I dont think i am getting exception as i can c the output once.What i am trying to do is repeat the process which i m getting once.What my method does is first one sends the packet to multicasting group (UDP) and other method receives the packets and prints.

  • A simple chat program

    for a simple chat progam which consists of a server and client, do i have to create 2 sockets to listen on the incoming and outing messengers or let 1 socket do those two things?

    you need one on the client side and another on the server side...
    you use on the client side :
    Socket mySocket=new Socket(ip,port);and on the server side:
    Socket mySocket=sSocket.accept(); //sSocket is an instance of ServerSocket

  • Chat program in release 4.7c

    hi guys,
    I was wondering how one can create a chat program in abap. As its possible in Java & .Net why an abaper under estimate himself. Now here imagine a simple chat program where one can send some text from his SAP GUI which will appear on others SAP GUI and viceversa. Dont think about some messangers like yahoo or gtalk.(dont over estimate being an abaper)
    So i developed two programs one to send text & other to receive text. Send prg. is module pool and receive prg. is a simple report which has timer class which gets data from table every second so user dont have to press any button to receive the message.
    To start chat you have to run both programs in your GUI where from send program you enter your name in one text field and your message in other text field by pressing enter it gets update in table field(not every time it insert new record, it simply update previous so table size would not increase). As the person with whoem you are chatting is also running both programs, your message appears in 2nd program on his GUI & yours also. followed by your name.
    Both chat programs works fine with more then two users also. i tried to combine both program in one screen so user can send & receive chat from one screen. but due to timer class used, its not possible as receive program keeps refreshing for every 1 second.
    so i am wondering is thier any way to run one modulepool program & one report in a single screen. some thing like screen splitting or docking???
    you are welcome to share your ideas regarding chat in ABAP/4(release 4.7)
    Regards,
    SUDHIR MANJAREKAR

    Yes, thats right. There are few ABAP codes which you can find in the net and can improvise on that.
    The program displays list of all users who are currently active on a list.
    You can select user and select press button on the application tool bar to send a message.
    Concerns here are: 1. The receiver cannot reply from the same popup. He has to run the program, select the user who has send message and reply. 2. You will not be able to see the entire message log.
    For logging messages you can try creating standard text for tracking dialog between any two user and something of that sort.
    regards,
    S. Chandramouli.

  • GUI for chat program

    Hi everyone,
    I'm writing a simple chat program as a assignment at my Uni. I get stucked with the client GUI. I want to create a GUI like that of Yahoo messenger which has a list of connected users displayed on the GUI. When u double click on the name of the user, u will get connected to that user. I have no idea about creating a GUI list like this one. Can anybody help me with this? Thanks in advance!

    There are many tutorials on this site; check the "tutorials" link on the column on the left.
    Here are ones about GUIs:
    http://developer.java.sun.com/developer/onlineTraining/GUI/
    I'd suggest skipping over any tutorials prior to JDK 1.1 or even 1.2.
    Read more recent ones. There have been significant improvements, especially w.r.t. event handling, between 1.0 and 1.1.

  • Problem with simple label program

    I'm getting a problem to a most basic program. I'm using the Java2 Fast And Easy Web Start book. This simple label program gives me an error when I compile. This is the program
    //Label Program
    //Danon Knox
    //Another basic program
    import java.awt.*;
    import java.applet.*;
    public class Label extends Applet{
      public void init(){
       Label firstlabel = new Label();
       Label secondlabel = new Label("This is the second label");
    //put the labels on the applet
      add(firstlabel);
      add(secondlabel);
    }// end init
    }// end appleterror when I compile is as follows:
    Microsoft Windows XP [Version 5.1.2600]
    (C) Copyright 1985-2001 Microsoft Corp.
    C:\>cd java
    C:\java>javac Label.java
    Label.java:12: cannot resolve symbol
    symbol : constructor Label (java.lang.String)
    location: class Label
    Label secondlabel = new Label("This is the second label");
    ^
    1 error
    C:\java>
    Can anyone help me?

    public class Label extends Applet{The name of your class is "Label". This choice of name hides the class named "Label" in java.awt.
    Label firstlabel = new Label();This creation of a Label is successful because the class has a default, no-argument constructor.
    Label secondlabel = new Label("This is the second label");And this one fails because there is no constructor for Label that takes a String argument.
    You probably want firstlabel and secondlabel to be java.awt.Label objects and not instances of your own Label class. Try this:
    public class Label extends java.applet.Applet{
        public void init(){
         java.awt.Label firstlabel = new java.awt.Label();
         java.awt.Label secondlabel =
             new java.awt.Label("This is the second label");
         add(firstlabel);
         add(secondlabel);
    }As a general remark, I advise programmers to stay away from
    import a.b.*;statements which import entire packages into your program namespace.
    When starting out, I believe it is better to write out the fully qualified names ot the classes and methods you are working with. This helps you learn the class hierarchy, and makes your code clearer.
    Others will disagree, but that's my opinion...

  • Simple sorting program for folders/files

    Hello comunity,
    I would like to make a simple sorting program which will scan through some folder looking for files with different extensions. Then copy files of the same format (example *.pdf) and (create) place them into folder with the name of the extension. After that the program (script) should look for another extension and do the similar operation to them untill all files will be moved. I am new to applescript and automator.app, so could you please put me on the right direction which programmin (script) language should I use. Sample code and good tips would be usefull too. Thank you for your time.

    This is not a hard thing to do. If you want to write it yourself, and have some background in programming, I recommend to read a book on AppleScript and start writing the code in AppleScript Editor.
    The AppleScript Language Guide is a free reference book by Apple which you can download it. There are a lot of sample codes on the net too.
    You should use the Finder dictionary to do this work. Finder is a scriptable application in Mac, which has a dictionary. This dictionary describes about the objects inside the finder that do all the duties of the Finder and you can call them directly in AppleScript to automate things. Open AppleScript editor, go to Window > Library and double click on Finder. This will open the dictionary. Note that all the objects in scriptable applications have a hierarchical relationship, starting from the root "application" object. You can read the dictionary to get familiar with the objects in the Finder app and know how to use them.
    Here is some code:
    tell application "Finder"
      tell the front window
      log (count of items of it)  -- prints the count of items in the window
      make new folder in it with properties {name:"mani"} -- makes a new folder named: mani
      make new file in it with properties {name:"test", extension:"txt"} -- makes a new text file
      repeat with x in every file in the items of it
          log the name of x
      end repeat
      end tell
    end tell
    If you can program in Objective-C and not have enough time to learn AppleScript, you can use Scripting Bridge technology to automate scriptable applications using Objective-C. This is so much better because enables you to debug your code or execute it line by line, which is not possible when working with AppleScript Editor.
    Hope this helps

  • Please help (Simple chat programme)

    I made a simple chat programme.
    It has a server object and it can handle several client.
    It is working properly and can use to chat.
    I have some problems. can you please help me.
    1.What is the best method to read input and outputStreams
    I have used inputStream.readUTF()/outputStream.writeUTF() methods and
    also I have used bufferedReader.readLine()/Printwriter.println() methods.
    I don't know about other methods.So please tell me what is the best and new out of these two.
    And are there any method which is better than these two.
    2.Is there any way to get more details from input and output streams
    Here more details means Fontcolor,Size etc;
    by now I'm adding them in to my output streams and filtering them when rea input stream.
    I'm getting other details(Fontcolor,Size) and add them all to a string.
    that means if client type "hi" my string will be something like this
    "12ff0000hi".
    When read the input stream i make a char[] and take first 2 chars to integer next six to a string and rest
    to another string.
    I think now you can understand my concept. So I'll not tell every thing.(if you want i can fully describe it)
    I' feeling this is very bad way to do that kind of work.
    Am i correct?
    so can you give me some hints or examples to do such kind of things.

    Here's a simple DataInputStream program that talks to itself. It runs the server as a seperate thread.
    import java.io.*;
    import java.net.*;
    public class DataXfer
            private int port = 5050;
            private String address="127.0.0.1";
            public static void main(String args[])
                    new DataXfer().startup();
            // run the server code as a thread and then run the client code
            private void startup()
                    new Thread(new Runnable(){public void run(){listen();}}).start(); // start server thread
                    synchronized(this){
                            try{wait();}catch(InterruptedException ie){}    // wait until its ready
                    connect();                                      // do client stuff     
            private void listen()
                    ServerSocket ss = null;
                    Socket us = null;
                    boolean running = true;
                    try{
                            System.out.println("Listening on port "+port);
                            synchronized(this){notify();}               // tell client we're ready
                            ss = new ServerSocket(port);    // listen for incoming connection
                            us = ss.accept();
                            ss.close();
                            ss = null;
                            DataInputStream dis = new DataInputStream(us.getInputStream());
                            try{
                                    while(running){
                                            int len = dis.readShort();      // read the count
                                            byte [] ba = new byte[len];
                                            int rlen = dis.read(ba,0,len);  // read the data
                                            System.out.println("len="+len+" read length="+rlen);
                                            if(rlen < len){
                                                    us.close();
                                                    running = false;
                                            else{
                                                    for(int j = 0; j<rlen; j++)System.out.print(ba[j]+" ");
                                                    System.out.println("");
                            catch(EOFException ee){System.out.println("EOF");}
                    catch(IOException ie){
                            ie.printStackTrace();
                            System.exit(0);
                    finally{
                            if(ss != null)try{ss.close();}catch(IOException se){}
                            if(us != null)try{us.close();}catch(IOException ue){}
            private void connect()
                    Socket us=null;
                    byte [] ba = new byte[31];
                    for(byte i = 0; i<ba.length; i++)ba=i;
    try{
    System.out.println("Connecting to "+address+":"+port);
    us = new Socket(address, port); // make connection
    System.out.println("Connected");
    DataOutputStream dos = new DataOutputStream(us.getOutputStream());
    for(int j = 0; j<ba.length;j+=10){
    dos.writeShort(j); // write the count
    dos.write(ba,0,j); // write the data
    System.out.println("sent "+j+" bytes");
    try{Thread.sleep(1000);}catch(InterruptedException ie){}
    catch(IOException ie){ie.printStackTrace();}
    finally{
    if(us != null)try{us.close();}catch(IOException ue){}
    For an example of a chat program using NIO see my NIO Server Example. That example is neither short nor simple.

  • Help with a simple Java program

    I'm making a sort of very simple quiz program with Java. I've got everything working on the input/output side of things, and I'm looking to just fancy everything up a little bit. This program is extremely simple, and is just being run through the Windows command prompt. I was wondering how exactly to go about making it to where the quiz taker was forced to hit the enter key after answering the question and getting feedback. Right now, once the question is answered the next question is immediately asked, and it looks kind of tacky. Thanks in advance for your help.

    Hmm.. thats not quite what I was looking for, I don't think. Here's an example of my program.
    class P1 {
    public static void main(String args[]) {
    boolean Correct;
    char Selection;
    int number;
    Correct = false;
    System.out.println("Welcome to Trivia!\n");
    System.out.println("Who was the first UF to win the Heisman Trophy?\n");
    System.out.print("A) Danny Wuerffel\nB) Steve Spurrier\nC) Emmit Smith\n");
    Selection = UserInput.readChar();
    if(Selection == 'B' | Selection == 'b')
    Correct = true;
    if(Correct == true)
    System.out.println("\nYou have entered the correct response.");
    else
    System.out.println("\nYou missed it, better luck next time.");
    System.out.println("(\nHit enter for the next question...");
    System.in.readLine();
    Correct = false;
    System.out.println("\nWhat year did UF win the NCAA Football National Championship?\n");
    number = UserInput.readInt();
    if(number == 1996)
    Correct = true;
    if(Correct == true)
    System.out.println("\nYou have entered the correct response.");
    else
    System.out.println("\nYou missed it, better luck next time.");
    Correct = false;
    System.out.println("\nWho is the President of the University of Florida?\n");
    System.out.println("A) Bernie Machen\nB) John Lombardi\nC) Stephen C. O'Connell\n");
    Selection = UserInput.readChar();
    if(Selection == 'A' | Selection == 'a')
    Correct = true;
    if(Correct == true)
    System.out.println("\nYou have entered the correct response.");
    else
    System.out.println("\nYou missed it, better luck next time.");
    }

  • VERY simple chat

    I've been playing around with network programming, and I'm trying to create a simple chat system. I've already got the client side done, but I'm wondering how I should do the chat server.
    I wanted the server to be something in the middle. Say I have two chat clients, I want the server to be running anonymously in the background relaying the messages back and forth. I'm just having problems figuring out how that I would get the server to register more than one client, and rely the message to the other clients.
    Could you guys give me some comments/suggestions on this? Does my idea sound dumb?

    Could you guys give me some comments/suggestions on
    this? Does my idea sound dumb?Not at all. Check these out for examples:
    http://www-106.ibm.com/developerworks/edu/j-dw-javachat-i.html
    http://access1.sun.com/codesamples/J2SE-MultiCastSockets.html
    http://www.cs.ucsb.edu/~cappello/290i/lectures/rmi/chatNew.html

  • Simple ftp program

    I'm looking for a simple ftp program for my MacBook.
    I've checked out Cyberduck, but it doesn't quite seem to be what I'm looking for.
    On my windows computer I use a program called FTP Commander, which has an extremely simple interface (http://chisuki.net/images/ftpscreencap.JPG <- screencap) and I'm looking for something about the same... except it has to be for Mac, of course..
    Also, it has to be freeware.
    Does anybody have any recommendations?

    It costs money, but I use Transmit...
    http://www.versiontracker.com/dyn/moreinfo/macosx/16683
    And it looks quite a bit like your JPG, though instead of Arrows
    <-
    ->
    You just double click on the side/file you want transfered.

  • Cannot use webcam with any chat programs - Satellite A200-AH7 Vista

    Satellite A200-AH7/Vista Home Premim/Chicony 2.0 USB built in webcam
    I can't seem to figure out how to get the audio working with the built in chicony webcam when in a chat program, or any program for that matter. I can record audio and playback later, but this is not what I want to do. It's probably just something silly I am missing..but any help sure would be appreciated...I have tried with Windows Live and Yahoo messenger and so far all I can do is wave at people LOL. I have never been able to make it work...any ideas?
    Today I have purchased a Logitech Quickcam for notebooks in case the problem is with the built in camera. I don't want to install it unless absolutely necessary and believe that I would need to uninstall the Chicony to make it work...can anyone point me in the right direction?
    I just want to be able to talk to my grandkids.....
    Thanks in advance,
    Sue

    Hi
    This is a Toshiba Canadian notebook model.
    You have to check the Toshiba Canadian website to get the right webcam software:
    http://209.167.114.38/support/TechSupport/ln_TechSupport.asp
    Remove firstly the old webcam software. Reboot the notebook. Clean the registry and system using the CCleaner (its free). Reboot the notebook again an then install the new webcam software!
    Greets

  • Simple OO program question

    Hi there,
    I would like to start writing some programs for myself now that I know a good part of the syntax of Java to keep learning in an intereseting way.
    But I have the problem that I still don't realy own the OO thinking to start a project.
    For example; I would like to write - to begin simple - a program that can add notes through a textfield and show the notes in a list or something like that.
    Also I would like to be able to save and load my notes list when I close and open the program respectively.
    I had thought of the following classes to use:
    - Main (for executing the program and calling the gui)
    - NotesGui (the actual window and swing components)
    - Note (a domain class representing a note with some attributes and methods)
    Is this a good idea? Or has somebody a better suggestion to start writing this little program?
    Help would be very appreciated ^^
    Thanks,
    Gert-Jan M.

    I am in a similar boat. I am new to Java and OO programming in general. For the record, I am using Java: How to Program as my book. The reason why I mention this will be clear. In my opinion you need to do a few things to get this project started. I myself and trying to think of a project to do in order to increase my skills. My opinion:
    In the book I am using, they have an ATM case study where they go through the complete process of creating an application. Their process follows a standard software development life cyle. What I can get from it so far is that the starting point is Requirements gathering. You need to write out in some detail what it is that you want your application to do. This shouldn't necessarily state the how or what technologies will be used. Once they have the requirements defined, they begin identifying potential classes from within the requirements document. I believe there are many ways to do this but in general they select all the nouns in the requirements document and start formulating their list where it makes sense. They also use UML and other tools to create class diagrams, use cases etc that help explain the interaction objects will have with one another. A lot of the upfront work is gathering requirements and desinging much of what you want to do prior to even coding. Since I'm new to this I'm sure other, more experienced developers could expand on this.
    My point is that you will want to understand the software development lifecycle and process, and learn more about software design. My personal end goal is to start learning design patterns and software development methodologies once I have a firm understanding of the Java language. Recommended readings could include the Deitel book Java: How to Program, Head First Object Oriented Analysis and Design, Head First Software Development and Head First Design Patterns. The Head First series seems nice because, in a somewhat easy fashion, they help explain software development processes, testing, software design, requirements gathering techniques and more. I think the sooner a developer learns about good design the better. I hope this helps.
    Edited by: lokus on Oct 3, 2008 12:04 PM

  • SSL simple chat

    Hallo,
    I did SSL simple chat, but something is wrong. This program is cennect to another same program(on localhost has diferent ports number). When send thread is weak up, NetBeans write this error: SEVERE: null
    java.net.UnknownHostException: java.
    I work with SSL fist time, I don´t know where I is error. I was inspire on this web side stilius.net/java/java_ssl.php and I use same keytool command. But I don´t know taht, I right use parametrs becouse I have server part and client part i one program.
    Could you check my code.
    import java.io.BufferedReader;
    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.OutputStream;
    import java.io.OutputStreamWriter;
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.net.ssl.SSLServerSocket;
    import javax.net.ssl.SSLServerSocketFactory;
    import javax.net.ssl.SSLSocket;
    import javax.net.ssl.SSLSocketFactory;
    * SslReverseEchoer.java
    * Copyright (c) 2005 by Dr. Herong Yang
    public class Main {
       public static void main(String[] args) {
           String addressIP;
           if(args.length==0)
                addressIP="127.0.0.1";
           else
               addressIP=args[0];
          ReciveThread recive = new ReciveThread();
          SendThread send = new SendThread(addressIP);
          recive.recive.start();
          send.send.start();
    class ReciveThread implements Runnable
    {   Thread recive;
        public ReciveThread()
            recive = new Thread(this,"Recive thread");
        public void run()
            try {
                SSLServerSocketFactory sslFactory = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
                SSLServerSocket sslServer = (SSLServerSocket) sslFactory.createServerSocket(5000);
                SSLSocket ssl = (SSLSocket) sslServer.accept();
                System.out.println("Adresa hostitele:"+ssl.getInetAddress().getHostName());
                while(true){
                    BufferedReader buffRead = new BufferedReader(new InputStreamReader(ssl.getInputStream()));
                    String line = null;
                    while((line = buffRead.readLine())!=null)
                        System.out.println("Recive data:"+line);
                        System.out.flush();
            } catch (IOException ex) {
    class SendThread implements Runnable
    {   Thread send;
        private String addressIP;
        public SendThread(String ip)
            this.addressIP=ip;
            send = new Thread(this,"Send thread");
        public void run()
            try {
                Thread.sleep(10000);
                SSLSocketFactory sslFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
                SSLSocket ssl = (SSLSocket) sslFactory.createSocket(this.addressIP,4000);
                BufferedReader buffKeyboard = new BufferedReader(new InputStreamReader(System.in));
                OutputStream outputStream = ssl.getOutputStream();
                BufferedWriter Buffwriter = new BufferedWriter(new OutputStreamWriter(outputStream));
                String radek = null;
                while((radek = buffKeyboard.readLine())!=null)
                    Buffwriter.write(radek+'\n');
                    Buffwriter.newLine();
                    Buffwriter.flush();
                    System.out.println("Posilana data:"+radek);
            } catch (InterruptedException ex) {
                Logger.getLogger(SendThread.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IOException ex) {
                Logger.getLogger(SendThread.class.getName()).log(Level.SEVERE, null, ex);
    }  

    OK i cut while(true){. This error write on this line: SSLSocket ssl = (SSLSocket) sslFactory.createSocket(this.addressIP,4000); . I think problem is somewhere in creating listen socket or wrong using parametrs for running programs. How can i put this:
    First copy certificate file that you created before into working directory and run server with these parameters (notice that you have to change keyStore name and/or trustStrorePassword if you specified different options creating certificate:
    java -Djavax.net.ssl.keyStore=mySrvKeystore -Djavax.net.ssl.keyStorePassword=123456 EchoServer
    And now again copy certificate file that you created before into working directory and run client with these parameters (notice that you have to change keyStore name and/or trustStrorePassword if you specified different options creating certificate:
    java -Djavax.net.ssl.trustStore=mySrvKeystore -Djavax.net.ssl.trustStorePassword=123456 EchoClient
    If i use server and client together in one program?

Maybe you are looking for

  • 4s not being recognized by iTunes, image capture, iPhoto or iMovie

    Hi i have a iphone 4s and i need to back everything up, mainly my videos. i plugged it into my mac and it's not being recognised on iTunes, iMovie, iPhoto or image capture and i have the latest OS X on both phone and mac and have the latest version o

  • Changes in basic start dates and its effects

    Dear All , Greetings!!!! Can you please guide me in "changes in basic start dates in Prod Ord". Actually,We are now starting to plan order creation as following parameters:                                                  Schedulling type:- Capacity

  • Missing Files after Lion Upgrade

    After upgrading to Lion I am missing files from a folder named "printers" I had created.  The previous os used a "printer" folder but not "printers".  It seems as if the Lion operating system deleted the existing folder and placed new files in there.

  • Backing up an unregistered Iphone before registering it?

    Hello, I am helping someone out with their Iphone 4 which they have been using for 6 months or so without registering it.  They need to register it to their computer now.  I am worried that by registering the Iphone all of the contacts on the phone w

  • OSX 10.9.1 Slow!

    For the past two weeks, my MacBookPro OSX 10.9.1 has been moving extremly slow. I clean out my cookies and delete temp files. I also use Clean My Mac on a regular basis. It's very frustrating when I'm working from home. Anyone else have this issue? I