Problem in server program: HELP!!!!
I just tried to introduce methods in my server program (TCPServer.java). the methods are
run_server() : for creating server socket object
[b[accept() [/b]: for Listening to a connection, made to the socket and accepting it.
getstreams() : initializing the streams
b]recieve_n_process() : receiving client input and processing it
send_response(): sending response back to client.
But now I am getting runtime exception
C:\Program Files\j2sdk_nb\j2sdk1.4.2\bin\abc>javac TCPServer.java
C:\Program Files\j2sdk_nb\j2sdk1.4.2\bin\abc>java TCPServer
Exception in thread "main" java.lang.NullPointerException
at TCPServer.accept(TCPServer.java:19)
at TCPServer.main(TCPServer.java:58)
C:\Program Files\j2sdk_nb\j2sdk1.4.2\bin\abc>
I know I might have made some silly mistake somewhere, please help me to detect it.
here is my code TCPServer.java
import java.io.*;
import java.net.*;
class TCPServer {
private ServerSocket welcomeSocket;
private Socket connectionSocket;
private ObjectInputStream Client_input;
private ObjectOutputStream Client_output;
private String clientSentence;
private String capitalizedSentence;
private void run_server() throws Exception
ServerSocket welcomeSocket = new ServerSocket(80);
private void accept() throws Exception
{connectionSocket = welcomeSocket.accept(); }
private void getstreams() throws IOException
Client_output = new ObjectOutputStream(connectionSocket.getOutputStream());
Client_output.flush();
Client_input = new ObjectInputStream(connectionSocket.getInputStream());
private void recieve_n_process() throws Exception
clientSentence = (String ) Client_input.readObject();
capitalizedSentence = clientSentence.toUpperCase() + '\n';
private void send_response() throws IOException
Client_output.writeObject(capitalizedSentence);
public static void main(String argv[]) throws Exception
TCPServer server = new TCPServer();
try{
server.run_server();
while(true) {
server.accept();
server.getstreams() ;
server.recieve_n_process();
server.send_response();
} catch(EOFException eofException) {}
catch (IOException ioException) {}
}It was working fine before I introduced these methods. Earlier it was like this
import java.io.*;
import java.net.*;
class TCPServer {
public static void main(String argv[]) throws Exception
String clientSentence;
String capitalizedSentence;
ServerSocket welcomeSocket = new ServerSocket(80);
while(true) {
Socket connectionSocket = welcomeSocket.accept();
ObjectInputStream inFromClient = new ObjectInputStream(connectionSocket.getInputStream());
ObjectOutputStream outToClient =
new ObjectOutputStream(connectionSocket.getOutputStream());
clientSentence = (String ) inFromClient.readObject();
capitalizedSentence = clientSentence.toUpperCase() + '\n';
outToClient.writeObject(capitalizedSentence);
hello every one,
i got it where is the problem. I had declared the object of ServerSocket class locally in run_server(). It had to be declared globally though.
private void run_server() throws Exception
ServerSocket welcomeSocket = new ServerSocket(80);
this one works out
private void run_server() throws Exception
welcomeSocket = new ServerSocket(80);
}
Similar Messages
-
Hi
My client prog runs in an infinite loop where it captures the screen and creates an image object.
After that it sends the image object to the server prog.
Server program receives it and displays it using Jframe , that is it uses a panel and a button named paste.
So I have used an infinite loop in the server side as well.
Problem is as long as client is running the interface that i used for pasting , pops up but I cant see the paste button
Its only when I close the client side the paste button becomes visible and its also working.
but I need to paste it even when the client side is running.
Any idea where am I going wrong?
The relevant codes are as follows----
SERVER:
public class Test
public Test() {
try {
ServerSocket ser=new ServerSocket(4444);
ImageIcon img=new ImageIcon();
String s1="1";
for(;;){
Socket clisoc=ser.accept();
DataOutputStream os1 = new DataOutputStream(clisoc.getOutputStream());
os1.writeUTF(s1);
ObjectInputStream oin = new ObjectInputStream(clisoc.getInputStream());
img=(ImageIcon)oin.readObject();
Image i =img.getImage();
Test1 e = new Test1(i);
System.out.println(i);
os1.close();
oin.close();
clisoc.close();
}catch(Exception e){}
}Test1 class is used for creating the image from the image object.
CLIENT---
public final class Test2 implements ClipboardOwner{
public static void main (String[] aArguments ){
try{
String s1;
for(;;){
Socket clisoc= new Socket("localhost",4444);
TextTransfer textTransfer = new TextTransfer();
DataInputStream dis=new DataInputStream(clisoc.getInputStream());
s1=dis.readUTF();
if(s1.equals("1")){
Robot robot=new Robot();
robot.keyPress(KeyEvent.VK_PRINTSCREEN);
robot.keyRelease(KeyEvent.VK_PRINTSCREEN);
BufferedImage g=(textTransfer.getClipboard());
ImageIcon ic = new ImageIcon(g);
System.out.println(ic);
ObjectOutputStream oos = new ObjectOutputStream(clisoc.getOutputStream());
Thread.sleep(9000);
oos.writeObject(ic);
dis.close();
oos.close();
clisoc.close();
else
continue;
}catch(Exception e){System.out.println(e);}
} getClipboard() is the function to catch the clipboard content.
Thanks in advance.Thanks for replying.
I got rid of the problem by introducing a similar if-else block in the server side as well.
Now I also dont have any Thread.sleep() in either client or server program.
The interface that I used to paste the image pops up alright but the paste button takes almost 3 minutes to appear.
Is it normal in windows 98 (P4)?Mind you , the button is working fine.
would you specify why should I "get rid of other close statements" except oos.close()?
I solved my previous problem by keeping them as it is. -
Problem in runing program help me please
hello friends
i m new user of java
i have installed java on my system
i set the path of java in environmenet varaibale by copying from program files C:\Program Files\Java\jdk1.6.0_07\bin and paste it followed by semi colons
when i run my program in command prompt
it compile the program but could not run it
it shows the follwoing error:-
" The java class could not be loaded.java.lang.unsupported class version Error:abc(unsupported major.minor version 50.0"
the net beans is also instakked on system but could not starts
plz help me fast.Judge wrote:
sir i will not understand wat u want to say???
whetehr i have to remove semicolon from the end of path in advance or i have to remove the full path of c:/program files/......OP, from the command prompt, try to run and compile as per the following:
C:\>"C:\Program Files\Java\jdk1.6.0_07\bin\javac" YourJavaApp.java
C:\>"C:\Program Files\Java\jdk1.6.0_07\bin\java" YourJavaAppIf this works, then just take the "C:\Program Files\Java\jdk1.6.0_07\bin" part - w/o the quotes - and place it at the beginning of your PATH. Oh, and if you have both a USER and SYSTEM PATH set, do it to both.
~Bill -
There was a problem starting C:\Program
Just used the Lenovo update gadget.
During reboot I get this message several times.
There was a problem starting C:\Program
HELP!Hi there,
Try downloading and running the print and scan doctor located here:
http://h10025.www1.hp.com/ewfrf/wc/document?docname=c03275041&cc=us&dlc=en&lc=en
It can fix a lot on its own and if not give a better idea of what is going on.
Best of Luck!
You can say thanks by clicking the Kudos Star in my post. If my post resolves your problem, please mark it as Accepted Solution so others can benefit too. -
HTTP Client/Server program problems
Hi all,
I am doing an exercise in which I create a Client and Server program. I send a GET request but nothing seems to happen. There is obviously something I'm missing. Could it be a badly formed request? The code is below. Any help is appreciated.
Client program.....
import java.io.*;
import java.net.*;
import java.util.StringTokenizer;
public class HTTPClient{
String host, path;
int port;
public static void main (String argv[]){
new HTTPClient(argv[0]);
public HTTPClient(String url){
try{
URL myURL = new URL(url);
host = myURL.getHost();
port = myURL.getPort();
System.out.println("Port = " + port);
if (port == -1) port = 30280;;
path = myURL.getPath();
if (path.equals("")) path = "/";
Socket s = new Socket(InetAddress.getByName(host), port);
sendRequest(s.getOutputStream());
printResponse(s.getInputStream());
s.close();
catch(MalformedURLException murl){
System.out.println("Badly formatted URL " + murl.getMessage());
catch(IOException e){
System.out.println("Problem initialising socket " + e.getMessage());
public void sendRequest(OutputStream out){
StringBuffer buf = new StringBuffer();
buf.append("GET /AC095.html HTTP/1.1\r\n");
buf.append("Host: http://students.odl.qmul.ac.uk\r\n\r\n");
try{
out.write(buf.toString().getBytes("US-ASCII"));
catch (IOException e) {System.out.println(e.getMessage());
public void printResponse(InputStream in){
try{
while (in.available() <= 0)
Thread.sleep(500);
while (in.available() > 0)
System.out.print((char) in.read());
System.out.println ("");
catch (IOException e) {
System.out.println(e.getMessage());
catch (InterruptedException ie) {
System.out.println("Error waiting for response " + ie.getMessage());
/* Read in the response from the HTTP server and print it out */
}Server code......
import java.io.*;
import java.net.*;
import java.util.*;
public class HTTPServer{
String version = null;
public String httpVer;
public static void main(String argv[]){
new HTTPServer(Integer.parseInt(argv[0]));
public HTTPServer(int port){
boolean listening = true;
try{
ServerSocket ss = new ServerSocket(port);
System.out.println("HTTP Server running and listening for requests...");
while (listening){
Socket mySocket = ss.accept();
InputStream in = mySocket.getInputStream();
readHeaders(in);
String response = getResponse();
OutputStream out = mySocket.getOutputStream();
out.write(response.getBytes("US-ASCII"));
out.flush();
mySocket.close();
catch(Exception e){System.out.println(e.getMessage());}
private String getResponse(){
StringBuffer responseBuf = new StringBuffer();
responseBuf.append (httpVer + " 200 OK\r\n");
responseBuf.append ("Content-type: text/html\r\n");
responseBuf.append ("Content-length: 119\r\n");
responseBuf.append ("<HTML>\r\n");
responseBuf.append ("<TITLE> My served web document </TITLE>\r\n");
responseBuf.append ("</HEAD>\r\n");
responseBuf.append ("<BODY>\r\n");
responseBuf.append ("<H1> Hello from the server! </H1>\r\n");
responseBuf.append ("</BODY>\r\n");
responseBuf.append ("</HTML>\r\n\r\n");
String responseStr = responseBuf.toString();
responseStr = responseStr.trim();
return "";
private void readHeaders(InputStream in) throws IOException {
StringBuffer sbuf = new StringBuffer();
int ch;
String clientStr;
//This loop reads in all of the input until there is nothing left to read.
//All of the characters are appended to the string buffer.
while ((ch = in.read()) != -1) {
sbuf.append((char) ch);
//clientStr will hold string in string buffer without any leading or
//trailing white space.
clientStr = sbuf.toString();
clientStr = clientStr.trim();
//Split clientStr into substrings and store them in an array.
String [] tokens = clientStr.split(" ");
//Obtains HTTP version
httpVer = tokens [2];
}Cheers,
ChrisI've written out.flush() in the server program. When I attempt to connect to the server it just hangs. I've modified the code locally to request a webpage from elsewhere and it works so it can't be the format of my GET request. I assume that the problem has to be in the Server program. Is it not reading in and understanding the /r/n properly?
-
i have a problem with xcode programming app when i lunch to it it asking me to enter my password and when i enter it the program show that it is wrong but am 100% sure it's wright so please help me with this issue thanks
That's not very intuitive
Check your mail server setup (mail>preferences>accounts>) choose your MobileMe account and select Outgoing Mail Server (SMTP) dropdown box, select Edit SMTP server list, verify that each instance of the me server has a password, if there are more than one and you only have one account then delete the one without a password. -
So I download photoshop cc (2014) and when I go to open the program, it gives me an error message and shuts the program down. It says," A problem cause the program to stop working correctly. Windows will close the program." Can someone help me please?
I've got the same issue and it affects all my adobe software. You are not alone as I have seen several postings looking for the answer to this help request.
-
[Window Title]
Microsoft Windows
[Main Instruction]
iTunes has stopped working
[Content]
A problem caused the program to stop working correctly. Windows will close the program and notify you if a solution is available.
[Close program]
This is what I got... sorry, not very tech savvy to copy the error message onto here...
Have tried uninstalled and re-installed iTune, updated the new version of 10.6... many times over still not working!!!
I share the frustrations of many here. HELP!!!!!Hi there Nok Saensanoh,
I would recommend taking a look at the troubleshooting steps found in the article below.
iTunes for Windows Vista, Windows 7, or Windows 8: Fix unexpected quits or launch issues
http://support.apple.com/kb/ts1717
-Griff W. -
i have a big problem why is it i cant update my ipod touch 2g into ios 4! im using the latest version of itunes and everytime i click "update" it stucks on the "contacting server" please help i want to update it now
Maybe here:
iTunes for Windows: iTunes cannot contact the iPhone, iPad, or iPod software update server -
how to solve the problem when opening program illustrator cs6
ERROR: 16
It is WINDOWS 8.1 / 64 BIT
help pleaseThanks, Jeff! The file Adobe Setup Error.log contains the following information:
02/14/14 07:20:26:474 | [INFO] | | OOBE | DE | | | | 8860 | DEVersion: 5.0.0.0
02/14/14 07:20:26:475 | [INFO] | | OOBE | DE | | | | 8860 | Loading library from C:\Program Files (x86)\Common Files\Adobe\OOBE\PDApp\DECore\DE5\Setup.dll
[ 8860] Fri Feb 14 07:20:26 2014 INFO
::START TIMER:: [Total Timer]
CHECK: Single instance running
CHECK : Credentials
Load Deployment File
CHECK : Another Native OS installer already running
Create Required Folders
Assuming uninstall mode
Lookup for master payload
[ 8860] Fri Feb 14 07:20:26 2014 ERROR
DW040: The product "{893B3B44-0A1E-404B-8FE8-0A74509102A9}" is not installed. Cannot proceed with the uninstall
[ 8860] Fri Feb 14 07:20:26 2014 INFO
:: END TIMER :: [Total Timer] took 6.90443 milliseconds (0.00690443 seconds) DTR = 579.338 KBPS (0.56576 MBPS)
-------------------------------------- Summary --------------------------------------
- 0 fatal error(s), 1 error(s), 0 warning(s)
ERROR: DW040: The product "{893B3B44-0A1E-404B-8FE8-0A74509102A9}" is not installed. Cannot proceed with the uninstall
Please search the above error/warning string(s) to find when the error occurred.
These errors resulted in installer Exit Code mentioned below.
Exit Code: 33 - The product is not installed, cannot uninstall.
Please see specific errors and warnings for troubleshooting. For example, ERROR: DW040 ... -
When opening Itunes, after placing my ID and password, I'm getting a message that indicates "Itunes has stopped working. A problem caused the program to stop working. Windows will close the program and will notify you if a solution is available. But I never get a response. Can somebody help?
Same exact thing with me. And no help from apple. Just dropped nearly $600 and cannot get a decent working setup.
Apple's only suggestion was to uninstall iTunes and Quicktime, and re-install... of course (the I.T. Crowd tactic).
The crash happens only on iTunes store access. -
Problem about loading server program to server
Hey Experts,
I'm facing an unexpected problem. I'm Using netbeans 6.1, JasperReport 3.7.0, iReport3.5.1 for creating a report.
I've successfully created a report using servlet. And after that I create a new report for another report. In this case,
netbeans shows me errors like:
org.apache.jasper.JasperException: java.lang.ClassCastException: org.apache.catalina.util.DefaultAnnotationProcessor cannot be cast to org.apache.AnnotationProcessor
org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:156)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:329)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:337)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:266)
javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:390)
I checked but could not find any problem. Can anybody help me with This?Note: This thread was originally posted in the [CLDC and MIDP|http://forums.sun.com/forum.jspa?forumID=76] forum, but moved to this forum for closer topic alignment.
-
Hello! Help me please, I have a problem with the program occurred after the upgrade to version 3. 6. 16, namely by pressing the button 'Open a new tab' nothing happens. ?
This issue can be caused by the Ask<i></i>.com toolbar (Tools > Add-ons > Extensions)
See:
* [[Troubleshooting extensions and themes]] -
I try to download my ebooks on my laptop but receive the onscreen message, Error getting license, License server commucication problem: E_ADEPT_NO_TOKEN. Please help?
It means, the URLLink.ACSM file is corrupted. Please contact the book store and ask them to check whether the configuration in the server side is correct for that book.
One of the simple setting in the server which can case this issue is, setting the book for loan in server and providing the purchase option in the book store or vise verse.
Hope this solves your problem. -
Hello,
I don't know much about threading, but I've got this server program (code follows). And where it does this... :
// Create a new thread for the connection
HandleAClient thread = new HandleAClient(connectToClient);
cn = clientNo;
// Start the new thread
thread.start();I need it to create another instance of the client program that accessing it with the same thread(I think, as i said I don't know much about threads). That way when a remote user accesses the client program, the server will automatically open another client program on the machine the server is running on. Then while their both using the same thread, they'll be able to speak back and forth without anyone else getting their text.
Does this make sense? Can anyone help?
Here is the server code, I don't have it perfected yet to send the text, but the clients will regester with the server.
// MultiThreadServer.java: The server can communicate with
// multiple clients concurrently using the multiple threads
import java.io.*;
import java.net.*;
import java.util.*;
// MultiThreadServer should be able to
// handle text from multiple users at once
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MultiThreadServer extends JFrame {
// Text area for displaying contents
private JTextArea jta = new JTextArea();
public static void main(String[] args) {
new MultiThreadServer();
public int cn = 0;
public MultiThreadServer() {
// Place text area on the frame
getContentPane().setLayout(new BorderLayout());
getContentPane().add(new JScrollPane(jta), BorderLayout.CENTER);
setTitle("MultiThreadServer");
setSize(500, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // It is necessary to show the frame here!
try {
// Create a server socket
ServerSocket serverSocket = new ServerSocket(8000);
jta.append("MultiThreadServer started at " + new Date() + '\n');
// Number a client
int clientNo = 1;
while (true) {
// Listen for a new connection request
Socket connectToClient = serverSocket.accept();
// Display the client number
jta.append("Starting thread for client " + clientNo +
" at " + new Date() + '\n');
// Find the client's host name, and IP address
InetAddress clientInetAddress =
connectToClient.getInetAddress();
jta.append("Client " + clientNo + "'s host name is "
+ clientInetAddress.getHostName() + "\n");
jta.append("Client " + clientNo + "'s IP Address is "
+ clientInetAddress.getHostAddress() + "\n");
// Create a new thread for the connection
HandleAClient thread = new HandleAClient(connectToClient);
cn = clientNo;
// Start the new thread
thread.start();
// Increment clientNo
clientNo++;
catch(IOException ex) {
System.err.println(ex);
// Inner class
// Define the thread class for handling new connection
class HandleAClient extends Thread {
private Socket connectToClient; // A connected socket
// Construct a thread
public HandleAClient(Socket socket) {
connectToClient = socket;
// Run a thread
public void run() {
try {
// Create data input and output streams
DataInputStream isFromClient = new DataInputStream(
connectToClient.getInputStream());
DataOutputStream osToClient = new DataOutputStream(
connectToClient.getOutputStream());
osToClient.writeDouble(cn);
// Continuously serve the client
while (true) {
// Receive radius from the client
double radius = isFromClient.readDouble();
// Compute area
double area = radius*radius*Math.PI;
// Send area back to the client
osToClient.writeDouble(area);
jta.append("radius received from client: " +
radius + '\n');
jta.append("Area found: " + area + '\n');
catch(IOException e) {
System.err.println(e);
}And here is the Client Program code, note that the sending of text does not yet work here either.
// Client.java: The client sends the input to the server and receives
// result back from the server
import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;
public class Client extends JFrame implements ActionListener {
// Text field for receiving radius
private JTextField jtf = new JTextField(40);
// Text area to display contents
private JTextArea jta = new JTextArea();
// IO streams
DataOutputStream osToServer;
DataInputStream isFromServer;
public static void main(String[] args) {
new Client();
public Client() {
// Ask the user for a name
String s = JOptionPane.showInputDialog
(null, "Please Enter Your Name:", "ZedX Web Messenger", JOptionPane.QUESTION_MESSAGE);
// Panel p to hold the label and text field
JPanel p = new JPanel();
p.setLayout(new BorderLayout());
p.add(new JLabel("Enter Text"), BorderLayout.WEST);
p.add(jtf, BorderLayout.CENTER);
p.add(new JButton("Go"), BorderLayout.EAST);
jtf.setHorizontalAlignment(JTextField.LEFT);
// jta.editable(false);
getContentPane().setLayout(new BorderLayout());
getContentPane().add(p, BorderLayout.NORTH);
getContentPane().add(new JScrollPane(jta), BorderLayout.CENTER);
jtf.addActionListener(this); // Register listener
String user = "Client";
setTitle(user);
setSize(500,500);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // It is necessary to show the frame here!
try {
// Create a socket to connect to the server
Socket connectToServer = new Socket("10.0.5.39", 8000);
// Create an input stream to receive data from the server
isFromServer = new DataInputStream(
connectToServer.getInputStream());
// Create an output stream to send data to the server
osToServer = new DataOutputStream(connectToServer.getOutputStream());
// Send client Name to server
// Get client number and name from server
double cn = isFromServer.readDouble();
user = user + " " + cn + ": " + s;
setTitle(user);
catch (IOException ex) {
jta.append(ex.toString() + '\n' + "Administrator must be offline, try again later.");
public void actionPerformed(ActionEvent e) {
String actionCommand = e.getActionCommand();
if (e.getSource() instanceof JTextField) {
try {
// Get the text from the text field
String radius = jtf.getText();
// Send the text to the server
osToServer.println(radius);
osToServer.flush();
// Get text from the server
double area = isFromServer.readDouble();
// Display to the text area
jta.append("You Sent: " + radius + "\n");
jta.append("Server" + area + '\n');
catch (IOException ex) {
System.err.println(ex);
}bump
Maybe you are looking for
-
Printing problem with Photosmart C4180
Hello, I'm trying to print invitations on my Photosmart C4180. I have a custom size of 6.25" by 6.25". The directions on the invitations say I should manually feed the paper. I can't find out how to do that. Do you have any suggestions? thank yo
-
Collection Question - Clearing a computer from one collection to another
Hey Guys, I have quick question. I have two collection , one for windows 7 and for windows 8. When adding a computer to my windows 8 collection, can I simply delete the old object from the windows 7 collection? Or is there a process for doing this? T
-
Need a clever solution for removing audio from the video gaps...
Here's a tiny section of my timeline: I want to delete all the audio in the areas where there's no video so that it looks like this: I was planning on just doing it manually one at a time, but my timeline is 3 hours long and there's over 500 gaps...
-
I have a lan with about 100 users all using Office 2000. All users are able to read embedded pdf files through Word except one. I have tried reinstalling Word and Acrobat Reader. I have tried older versions of Reader too. All efforts fail, clicking o
-
Dear All, Is there any standard report available for following, 1. Monthly/Yearly report of items indented, on Cost Center wise 2. Report of Equipments Sub-contracted If standard reports are not available, is there any work around to get these report