Java:Socket编程
1.Server端
import java.io.*; import java.net.*; import java.util.*; public class Server{ public final static int PORT = 6666; public static void main(String[] args){ ServerSocket ss = null; DataInputStream dis = null; DataOutputStream dos = null; Socket s = null; try{ ss = new ServerSocket(PORT); while(true){ System.out.println("wait for client..."); s = ss.accept(); System.out.println("client link success!"); dis = new DataInputStream(s.getInputStream()); dos = new DataOutputStream(s.getOutputStream()); new Thread(new ServerSend(dos)).start(); new Thread(new ServerRecv(dis)).start(); } }catch(Exception e){ e.printStackTrace(); } } } //启动新的线程发送信息给Client class ServerSend implements Runnable{ private DataOutputStream dos = null; public ServerSend(DataOutputStream dos){ this.dos = dos; } public void run(){ Scanner sc = new Scanner(System.in); while(true){ try{ String content = sc.nextLine(); System.out.println("Server: " + content); dos.write(content.getBytes()); dos.flush(); }catch(Exception e){ e.printStackTrace(); } } } } //启动新的线程接收Client发来的信息 class ServerRecv implements Runnable{ private DataInputStream dis = null; public ServerRecv(DataInputStream dis){ this.dis = dis; } public void run(){ try{ byte[] buffer = new byte[1024*10]; int length = -1; while((length = dis.read(buffer)) != -1){ String str = new String(buffer,0,length); System.out.println("Client: "+str); } }catch(Exception e){ e.printStackTrace(); } } }
2.Client端
import java.io.*; import java.net.*; import java.util.*; public class Client{ public final static String IP = "127.0.0.1"; public final static int PORT = 6666; public static void main(String[] args){ Socket s = null; DataInputStream dis = null; DataOutputStream dos = null; try{ System.out.println("start link sever..."); s = new Socket(IP,PORT); System.out.println("link sever success!"); dis = new DataInputStream(s.getInputStream()); dos = new DataOutputStream(s.getOutputStream()); new Thread(new ClientRecv(dis)).start(); new Thread(new ClientSend(dos)).start(); }catch(Exception e){ e.printStackTrace(); } } } //启动新的线程发送信息给Server class ClientSend implements Runnable{ private DataOutputStream dos = null; public ClientSend(DataOutputStream dos){ this.dos = dos; } public void run(){ Scanner sc = new Scanner(System.in); while(true){ try{ String content = sc.nextLine(); System.out.println("Client: " + content); dos.write(content.getBytes()); dos.flush(); }catch(Exception e){ e.printStackTrace(); } } } } //启动新的线程接收Server发来的信息 class ClientRecv implements Runnable{ private DataInputStream dis = null; public ClientRecv(DataInputStream dis){ this.dis = dis; } public void run(){ try{ byte[] buffer = new byte[1024*10]; int length = -1; while((length = dis.read(buffer)) != -1){ String str = new String(buffer,0,length); System.out.println("Server: "+str); } }catch(Exception e){ e.printStackTrace(); } } }
3.测试结果

http://www.cnblogs.com/makexu/

浙公网安备 33010602011771号