0

I have written a client server program:

 { import java.net.*; class verify { public static int serverPort=998; public static int clientPort=999; public static int buffer_size=1024; public static DatagramSocket ds; public static byte buffer[]=new byte[buffer_size]; public static void TheServer() throws Exception { int pos=0; while (true) { int c=System.in.read(); switch(c) { case -1: System.out.println("server quits"); return; case '\r': break; case '\n': ds.send(new DatagramPacket(buffer,pos,InetAddress.getLocalHost(),clientPort)) ; pos=0; break; default: buffer[pos++] = (byte) c; } } } public static void TheClient()throws Exception { while(true) { DatagramPacket p=new DatagramPacket(buffer,buffer.length); ds.receive(p); System.out.println(new String(p.getData(),0,p.getLength())); } } public static void main(String args[]) throws Exception{ if(args.length==1) { ds=new DatagramSocket(serverPort); TheServer(); } else { ds=new DatagramSocket(clientPort); TheClient(); } } } } 

Can I make my pc both server and client.If yes please suggest a way out.

2
  • Please use the code formatting feature. The code in your post is difficult to read. Commented Mar 23, 2011 at 5:56
  • @ Mudassir improved the code Commented Mar 23, 2011 at 6:10

2 Answers 2

1

Yes, your PC can absolutely be both the server and the client. How to get there from your code I cannot say, however.

Generally though, in TheServer() you will want to create a ServerSocket and set it to listen on serverPort. Then do something like Socket clientSocket = serverSocket.accept() to wait for and accept the next incoming connection.

Then in TheClient() you create a new Socket to "localhost" on serverPort. This will connect your server and client.

Note that because serverSocket.accept() blocks, your server and client cannot share the same thread. So you can either run two separate instance of your application as you seem to be doing now, or you can use main() to set up a new thread for TheServer() and then start it before you call TheClient().

Sign up to request clarification or add additional context in comments.

2 Comments

@Suhail - Thanks, that's much more readable. Is there any particular reason why you're using DatagramSocket instead of ServerSocket and Socket?
No,not any particular reason.I just want to pass messages
0

As long as the client and server sends and receives on different ports, then there is no reason that you cannot have both client and server running on the same machine. In fact, I did this quite often during my university years while I was testing client/server applications.

1 Comment

@Suhail Gupta - No, different. So use, for example, 3000 for server sending, 3001 for server listening, 3002 for client sending and 3003 for client listening.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.