Java套接字编程

Java客户端与服务器:
先启动服务器,再启动客户端



//Server.java
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
 public static void main(String[] args) throws Exception {
  int port = 12345;
  ServerSocket server = new ServerSocket(port);
  System.out.println("服务器就绪,等待用户登录:");
  Socket so = server.accept();
  byte[] buff = new byte[1024];
  int read = so.getInputStream().read(buff);
  String str = new String(buff,0,read);
  String[] split = str.split(",");
  for(int i=0; i<split.length; i++)
   System.out.println(split[i]);
  so.close();
  server.close();
 }
}




//Client.java
import java.net.Socket;
public class Client {
 public static void main(String[] args) throws Exception {
  int port = 12345;
  System.out.print("在此输入用户名和密码,并用','分开:");
  byte[] buff = new byte[1024];
  int read = System.in.read(buff);
  String str = new String(buff,0,read);
  Socket so = new Socket("localhost",port);
  so.getOutputStream().write(str.getBytes());
  so.getOutputStream().flush();
  so.getOutputStream().close();
  so.close();
 }
} 

两个例子:http://www.enet.com.cn/article/2007/1024/A20071024880926.shtml
http://www.51testing.com/?uid-202848-action-viewspace-itemid-122114

你可能感兴趣的:(java,编程,.net,socket)