socket实现一对一通讯

客户端发出信息

package socketoneToone;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;

/**
 * Created by Administrator on 2015/10/30 0030.
 */
public class Client {
    public static void main(String[] args) throws IOException {
        Socket socket=new Socket("127.0.0.1",8081);
        BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        bw.write("Hello World");
        bw.flush();
        socket.close();
    }
}


服务器端接收

package socketoneToone;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created by Administrator on 2015/10/30 0030.
 */
public class Server {
    public static void main(String[] args) throws IOException {
        ServerSocket ss=new ServerSocket(8081);
        Socket socket=ss.accept();
        BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String str="";
        while((str=br.readLine())!=null){
            System.out.println(str);
        }
        socket.close();
    }

}



你可能感兴趣的:(socket,通讯)