java socket 通讯

java 教程上的socket通讯只能客户端向服务器发送信息,让很多入门的朋友为难,

在这里我为朋友展示双向通讯,谢谢支持!

//以下是客户端

import java.io.*;
import java.net.*;
public class SockClient{
static Socket ssock;
static String line;
static BufferedReader wt;
static PrintWriter out;
static BufferedReader in ;
public static void main(String args[]) throws IOException {
try{
ssock =new Socket("127.0.0.1",30000);
in =new BufferedReader(new InputStreamReader(ssock.getInputStream()));
out =new PrintWriter(ssock.getOutputStream());
wt=new BufferedReader(new InputStreamReader(System.in));
}
catch(Exception e){
System.out.println("连接失败");
}
threadchat t=new threadchat();
threadchat1 t1=new threadchat1();
t.start();
t1.start();


}
//线程0
static class threadchat extends Thread {
public void run(){
try{
while(true){
System.out.println("线程0启动");
System.out.println(in.readLine());}
}
catch(Exception e){}
}}


//线程1
static class threadchat1 extends Thread {
public void run(){
try{
while(true){
System.out.println("线程1启动");
line=wt.readLine();
out.println(line);
out.flush();}
}
catch(Exception e){}
}}

}

以下是服务端
import java.io.*;
import java.net.*;

public class SockServer{
static String line;
static BufferedReader wt;
static PrintWriter out;
static BufferedReader in ;
public static void main(String args[]) throws IOException {
try{
ServerSocket ssock=new ServerSocket(30000);
Socket csock =ssock.accept();
in=new BufferedReader(new InputStreamReader(csock.getInputStream()));
out=new PrintWriter(csock.getOutputStream());
wt=new BufferedReader(new InputStreamReader(System.in));
}
catch(Exception e){
System.out.println("连接出错,超哥为你提醒");
}
threadchat t=new threadchat();
threadchat1 t1=new threadchat1();
System.out.println("连接成功"); //超哥好男人
t.start();
t1.start();


}

//版权保留,转摘请注明出处,chaohena1314新浪
//线程0
static class threadchat extends Thread {
public void run(){
try{
while(true){
System.out.println("线程0启动");
out.println(wt.readLine());
out.flush();}
}
catch(Exception e){}
}}

//线程1
static class threadchat1 extends Thread {
public void run(){
try{
while(true){
System.out.println("线程1启动");
line=in.readLine();
System.out.println(line);
line=in.readLine();}
}
catch(Exception e){}
}}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值