一个完整的Socket例子

本文提供了一个Java Socket通信的完整示例,包括服务端和客户端的实现代码。服务端监听765端口,与客户端进行UTF字符串形式的数据交换,实现了简单的数值递增功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一个完整的Socket例子

以下程序在Jbuilder4下调试成功![下载源程序]
服务端的程序:
[code]
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();
}
}
[/code]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值