用Socket建立个最简单的聊天程序

2008-02-23 10:08:05来源:互联网 阅读 ()

新老客户大回馈,云服务器低至5折

用Socket建立个最简单的聊天程序

Java、Socket、网络编程、聊天

/*一个作为Server*/
import java.io.*;
import java.net.*;
public class MyServer{
public static void main(String[] args)
throws IOException{
ServerSocket s=new ServerSocket(8658);
System.out.println("开始:" s);
try{
Socket socket=s.accept();
try{
System.out.println("连接接受" socket);
BufferedReader in=new BufferedReader(new InputStreamReader
(socket.getInputStream()));
PrintWriter out=new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),true);
while(true){
String str=in.readLine();
if(str.equals("q")) break;
System.out.println("对方说:" str);
BufferedReader is=new BufferedReader(new InputStreamReader(System.in));
String input=new String();
input=is.readLine().trim();
out.println(input);
System.out.print("我说:");
out.flush();
}
}
finally{
System.out.println("关闭....");
socket.close();
}
}
finally{
s.close();
}
}
}

/*一个作为Client*/
import java.io.*;
import java.net.*;
public class MyClient{
public static void main(String[] args)
throws IOException{
InetAddress addr=InetAddress.getByName("127.0.0.1");
System.out.println("地址=" addr);
Socket socket=new Socket(addr,8658);
try{
System.out.println("socket=" socket);
BufferedReader is=new BufferedReader(new InputStreamReader(System.in));
PrintWriter out=new PrintWriter(socket.getOutputStream(),true);
for(;;){
System.out.print("我说:");
String input=new String();
input=is.readLine().trim();
out.println(input);
if(input.equals("q")) break;
BufferedReader in=new BufferedReader(new InputStreamReader
(socket.getInputStream()));
String str=in.readLine();
System.out.println("对方说:" str);
out.flush();
}

}
finally{
System.out.println("关闭");
socket.close();
}
}
}

上一篇: 用Socket建立简单的TCP/IP服务
下一篇: 用Socket建立简单的C/S结构的TCP/IP服务

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:jsp mysql制作简单的留言板(5)

下一篇:在JSP网页上实现月历