网络编程分两种,一种是TCP编程,还有一种是UDP编程(点击打开链接)。而本文先讲述简单的TCP编程,Socket套接字连接通讯,实现简单的client与server之间的信息传输。
以下是client与server之间简单的传输数据(单对单):
注意:服务端先启动。然后再启动client。
client:
public class C {
public static void main(String[] args) {
try {
Socket s = new Socket("172.18.122.64", 10086); //訪问服务端是本地server,port号是10086,要同样
if(s.isConnected()){
System.out.println("client成功连接");
}
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
Scanner in = new Scanner(System.in);
/*GetMsg get = new GetMsg(s);
get.start();*/
while(true){
String s1 = in.next();
if(s1.equals("exit")){
break;
}
bw.write(s1);
bw.newLine();
bw.flush();
}
bw.close();
s.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } }
服务端:
public class S {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(10086); //服务端,port是10086
Socket s = server.accept(); //開始监听连入的客户port
String clientip = s.getInetAddress().getHostAddress(); //获得客户端ip地址
System.out.println("连入服务器的是来自:"+clientip);
boolean flag = true;
GetMsg get = new GetMsg(s);
get.start();
/*SendMsg send = new SendMsg(s);
send.start();*/
while(flag){ }
s.close();
server.close(); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} }
public class GetMsg extends Thread {
private Socket s;
public GetMsg(Socket s){
this.s = s;
}
@Override
public void run() {
// TODO Auto-generated method stub
BufferedReader br;
String str;
try {
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
boolean flag = true;
while(flag){
if((str=br.readLine())!=null){
System.out.println(str);
}
}
br.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } }
实验结果:
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">
watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="">
以上实现的是client与server端一对一之间的通讯。也能够实现多人聊天的功能,而server在这之间的角色就相当于中介。负责转发信息。假设须要多人聊天的能够留下邮箱或qq号我发给你。