以下程序在jbuilder4下调试成功![下载源程序]
服务端的程序:
import java.io.*;
import java.net.*;
public class socketserver {
serversocket ss=null;
socket s=null;
datainputstream instream=null;
dataoutputstream outstream=null;
public socketserver() {
try{
init();
}
catch(exception e){
system.out.println(e.tostring());
}
}
void init() throws exception{
ss=new serversocket(765);
s.setsotimeout(3000);
}
void waitforclient(){
try{
s=ss.accept();
instream=new datainputstream(s.getinputstream());
outstream=new dataoutputstream(s.getoutputstream());
outstream.writeutf("1");
s.setsotimeout(3000);
waitdata();
}
catch(exception e){
system.out.println(e.tostring());
}
}
void waitdata(){
while(true){
try{
string str=instream.readutf();
system.out.println("server accept: "+str);
int nu=integer.parseint(str)+1;
if(nu>20){
system.out.println("send end!");
break;
}
else{
str=integer.tostring(nu);
outstream.writeutf(str);
}
}
catch(exception e){
system.out.println(e.tostring());
break;
}
}
}
public static void main(string[] args) {
socketserver socketserver1 = new socketserver();
socketserver1.waitforclient();
}
}
客户端的程序:
import java.net.*;
import java.io.*;
public class socketclient{
socket s=null;
datainputstream instream=null;
dataoutputstream outstream=null;
public socketclient() {
try{
init();
waitdata();
}
catch(exception e){
system.out.println(e.tostring());
}
}
void init() throws exception{
s=new socket("192.168.0.32",765); //把这里的ip改成你运行socketserver.class的ip
instream=new datainputstream(s.getinputstream());
outstream=new dataoutputstream(s.getoutputstream());
s.setsotimeout(3000);
}
void waitdata(){
while(true){
try{
string str=instream.readutf();
system.out.println("client accept: "+str);
str=integer.tostring(integer.parseint(str)+1);
outstream.writeutf(str);
}
catch(exception e){
system.out.println(e.tostring());
break;
}
}
}
public static void main(string[] args) {
socketclient socketclient1 = new socketclient();
}
}
闽公网安备 35060202000074号