简单的一个socket通信
//客户机
package Client;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Client {
public static void main(String args[]){
String host= "172.31.18.85";
int port=65200;
PrintWriter pw ;
BufferedReader br;
String CilentSay;
String temp;
try {
Socket socket = new Socket(host,port);
//状态提示
System.out.println("你已经成功链接服务端。。。");
Scanner in = new Scanner(System.in);
while(true){
//接受来自服务器的消息
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
temp =br.readLine();
System.out.print(" 主服务器发来消息:");
System.out.println(temp);
//向服务起发送消息
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
System.out.print(" 向主服务器发消息:");
CilentSay=in.nextLine();
pw.println(CilentSay);
pw.flush();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//服务器
package Server;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server {
public static void main(String args[]){
PrintWriter pw;
String temp;
String serverSay;
BufferedReader br;
try {
ServerSocket serversocket = new ServerSocket(65200);
System.out.println("服务器启动了...");
Socket socket = serversocket.accept();
System.out.println("客户机链接服务器");
Scanner in =new Scanner(System.in);
while(true){
//向客户机发送消息
pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
System.out.print(" 向客户机发消息:");
serverSay=in.nextLine();
pw.println(serverSay);
pw.flush();
//接受来自客户机的消息
br = new BufferedReader
(new InputStreamReader(socket.getInputStream()));
temp = br.readLine();
System.out.print(socket.getInetAddress()+" 发来消息:");
System.out.println(temp);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
遇到的困惑
这个socket用了一晚上才写出来,一直只能单向通讯,或者每次只能互发一条消息,最后我将我的发送消息的代码
`while(in.hasNext()){
serverSay=in.nextLine();
pw.println(serverSay);
pw.flush();}
改 成
serverSay=in.nextLine();
pw.println(serverSay);
pw.flush();
去掉那个循环就能实现多次双向通信,有知道的同学请评论一下,向你请教一下。