我如何在服务器上编译我的服务器代码?

时间:2014-02-14 04:41:59

标签: java sockets

我是套接字编程的新手。 我有两个java程序(Client.java和Server.java),对于socket编程,我想将我的server.java代码编译到服务器,它始终监听socket,但我不知道我在服务器上做了什么。

Server.java

import java.lang.*;
 import java.io.*;
  import java.net.*;

 class Server {
public static void main(String args[]) {
   String data = "Toobie ornaught toobie";
  try {
     ServerSocket srvr = new ServerSocket(1234);
     Socket skt = srvr.accept();
     System.out.print("Server has connected!\n");
     PrintWriter out = new PrintWriter(skt.getOutputStream(), true);
     System.out.print("Sending string: '" + data + "'\n");
     out.print(data);
     out.close();
     skt.close();
     srvr.close();
  }
  catch(Exception e) {
     System.out.print("Whoops! It didn't work!\n");
  }
 }
  } 

Client.java

    import java.lang.*;
     import java.io.*;
      import java.net.*;

      class Client {
 public static void main(String args[]) {
   try {
     Socket skt = new Socket("localhost", 1234);
     BufferedReader in = new BufferedReader(new
        InputStreamReader(skt.getInputStream()));
     System.out.print("Received string: '");

     while (!in.ready()) {}
     System.out.println(in.readLine()); // Read one line and output it

     System.out.print("'\n");
     in.close();
  }
  catch(Exception e) {
     System.out.print("Whoops! It didn't work!\n");
  }
  }
  }

2 个答案:

答案 0 :(得分:1)

搜索如何编译Java文件。在您的情况下,将javac Server.java编译它,然后java Server运行。客户也是如此。

答案 1 :(得分:0)

明白了。 http://www.careerbless.com/samplecodes/java/beginners/socket/SocketBasic1.php

这里服务器总是听客户端。 谢谢你们的帮助。