导航:首页 > 编程语言 > socketjava源代码

socketjava源代码

发布时间:2025-06-11 21:27:39

1. java socket网络编程

//==============Server.java=================//
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
public static void main(String[] args) throws IOException {
ServerSocket s = new ServerSocket(12345);
System.out.println("服务器就绪,请启动客户端.");
Socket so = s.accept();
byte[] buff = new byte[1024];
int read = so.getInputStream().read(buff);
String[] abc=new String(buff,0,read).split("\\D+");
int a = Integer.parseInt(abc[0]);
int b = Integer.parseInt(abc[1]);
int c = Integer.parseInt(abc[2]);
if(!cbt(a,b,c))
so.getOutputStream().write("输入的数据无法组成三角形.".getBytes());
else
so.getOutputStream().write(getArea(a,b,c).getBytes());
so.getOutputStream().flush();
so.close();
s.close();
}

private static String getArea(int a, int b, int c) {
float s = (a+b+c)/2f;
return "面积: "+Math.sqrt(s*(s-a)*(s-b)*(s-c));
}

private static boolean cbt(int a, int b, int c) {
return a>0&&b>0&&c>0&&a+b>c&&b+c>a&&a+c>b;
}
}

//=================Client.java======================//
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client {
public static void main(String[] args) throws UnknownHostException, IOException {
System.out.println("输入三角形的三边并用逗号隔开,如: (3,4,5) ");
byte[] buff=new byte[64];
int r = System.in.read(buff);
String ipaddr = "localhost";//根据情况改变,在本机调试就不改了
Socket so = new Socket(ipaddr,12345);
so.getOutputStream().write(new String(buff,0,r).getBytes());
r = so.getInputStream().read(buff);
so.close();
String rs = new String(buff,0,r);
System.out.println(rs);
}

}

//先启动Server,再启动Client

2. Java TCP socket通信,如何实现发送十六进制值,并在数据接收窗口中显示这些数据对应的字符串,非常感谢!

我自己的电脑上有一段源代码,就是基于TCP聊天小代码,能进行相互之间的消息接受。我的代码是直接传输字符串的,不是16进制滴。嗯,也贴出来看看吧!

运行服务器,c1,c2就可以了,c1与c2可进行通信。

Client.java

import java.net.*;
public class Client{
static byte num=1;
private int portNum;

public Client(int portnum){
this.portNum=portnum;
System.out.println("您是第"+num+"位客服端");
num++;
}

public void sentMessage(String me){
//都是向服务器发信息端口号1999
try{
DatagramSocket ds=new DatagramSocket();
DatagramPacket dp=new DatagramPacket(me.getBytes(),me.length(),InetAddress.getByName("127.0.0.1"),1999);
ds.send(dp);
ds.close();
}catch(Exception e){
e.printStackTrace();
}

}

public String receiveMessage(){
String str="";
try{
DatagramSocket ds=new DatagramSocket(this.portNum);//表示哦自己的接收端口号是1999
byte[] buf=new byte[1024];
DatagramPacket dp=new DatagramPacket(buf,1024);
ds.receive(dp);
str=new String(dp.getData(),0,dp.getLength());
ds.close();
}catch(Exception e){
e.printStackTrace();
}

return str;
}
}

c1.java

import java.util.*;
public class c1 implements Runnable{
Client cl;
boolean goon=true;
Scanner sc=new Scanner(System.in);
public c1(){
cl=new Client(2000);
System.out.println("这里是2000客户端\n你可以发送信息。请输入要发送的信息。out退出");

new Thread(this).start();
while(this.goon==true){
say();
}
if(goon==false){
System.exit(0);
}
}

public static void main(String[] args){
new c1();
}

public void say(){
String mess=sc.nextLine();
System.out.println("是否发送y/n");
String key=sc.nextLine();
if(key.equals("y")){
System.out.println("信息信息发送中……");
try{
cl.sentMessage(mess);
}catch(Exception e){
e.printStackTrace();
}
}
else if(key.equals("out")){
goon=false;
}
}

public void run(){
while(this.goon==true){
String sst="";
try{
sst=cl.receiveMessage();
}catch(Exception e){
e.printStackTrace();
}

if(sst.length()>0){
System.out.println(sst);
}
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}

}
System.out.println("程序结束!");
}
}

c2.java

import java.util.*;
public class c2 implements Runnable{
Client cl;
boolean goon=true;
Scanner sc=new Scanner(System.in);
public c2(){
cl=new Client(2001);
System.out.println("这里是2001客户端\n你可以发送信息。请输入要发送的信息。out退出");
new Thread(this).start();
while(goon==true){
say();
}
if(goon==false){
System.exit(0);
}
}

public static void main(String[] args){
new c2();
}

public void say(){
String mess=sc.nextLine();
System.out.println("是否发送y/n");
String key=sc.nextLine();
if(key.equals("y")){
System.out.println("信息信息发送中……");
try{
cl.sentMessage(mess);
}catch(Exception e){
e.printStackTrace();
}
}
else if(key.equals("out")){
this.goon=false;
}
}

public void run(){
while(this.goon==true){
String sst="";
try{
sst=cl.receiveMessage();
}catch(Exception e){
e.printStackTrace();
}

if(sst.length()>0){
System.out.println(sst);
}
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}

}
System.out.println("聊天关闭!");
}
}

Server.java

import java.net.*;
import java.util.*;
public class Server implements Runnable{
private String message;
boolean work=true;
byte tm=10;
String[] clomessage={"信息:正在断开网络连接.",".",".\n","信息:设置保存中……","","","完成\n","信息:欢迎下次使用\n","信息:完成\n","Goodbye!"};
public Server(){
new Thread(this).start();
System.out.println("本程序为服务端Server");
Scanner sc=new Scanner(System.in);
System.out.println("输入命令out关闭服务器");
String clo=sc.nextLine();
if(clo.equals("out")){
System.out.println("正在关闭服务器……");
setwork(false);
System.exit(0);
}

}

public static void main(String[] args){
new Server();

}

public void setwork(boolean bo)
{
this.work=bo;
}

public void setMessage(String str){
this.message=str;
}

public String getMessage(){
return this.message;
}

public void sentMessage(){
String mes=this.getMessage();
try{
DatagramSocket ds=new DatagramSocket();
DatagramPacket dp=new DatagramPacket(mes.getBytes(),mes.length(),InetAddress.getByName("127.0.0.1"),2000);
DatagramPacket dp2=new DatagramPacket(mes.getBytes(),mes.length(),InetAddress.getByName("127.0.0.1"),2001);
ds.send(dp);
ds.send(dp2);
ds.close();
System.out.println("信息发送至:127.0.0.1:2000 & 127.0.0.1:2001");
this.setMessage("");
}catch(Exception e){
e.printStackTrace();
}
}

public void receiveMessage() throws Exception{
try{
DatagramSocket ds=new DatagramSocket(1999);//表示哦自己的接收端口号是1999
byte[] buf=new byte[1024];
DatagramPacket dp=new DatagramPacket(buf,1024);
ds.receive(dp);
String str=new String(dp.getData(),0,dp.getLength());
if(str.length()>0){
this.setMessage(str);
System.out.println("信息:Server从"+dp.getAddress().getHostAddress()+"主机(端口号:"+dp.getPort()+")收到信息:"+this.getMessage());
}

ds.close();
}catch(Exception e){
e.printStackTrace();
}
}

public void run(){
while(tm>0){
if(work==false){
tm--;
System.out.print(clomessage[9-tm]);
}
try{
receiveMessage();//时刻接受信息
}catch(Exception e){
e.printStackTrace();
}

if(this.getMessage().length()>0){//如果接收到信息则发送信息

try{
sentMessage();
}catch(Exception e){
e.printStackTrace();
}
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}

}
}
}
}

呵呵,请指教啊!

3. java 聊天室 源代码

最简单的聊天室

4. java socket如果服务端掉线 客户端应该怎样重连,实现的思路是怎么样的,最好能有具体的代码参考一下

看代码,不明白的追问

// 无穷循环,用于自动重新连接网关
while (true) {
// 捕获sleep异常
try {
// 捕获socket异常
try {
// 创建socket连接
socketGateway = new Socket("127.0.0.1", 8888);

// 创建输入输出对象
inStream = new DataInputStream(socketGateway.getInputStream());
outStream = new DataOutputStream(socketGateway.getOutputStream());

byte buf[] = new byte[1]; // 数据缓冲区
int intLen; // 读缓冲区返回的长度

// 无穷循环,用于读缓冲区数据
while (true) {
// 捕获读缓冲区异常
try {
intLen = inStream.read(buf, 0, 1);

// 可读长度-1则断开连接
if (intLen == -1) {
break;
}

// 处理buf
}

// 连接断开
catch (EOFException e) {
break;
}

// 接收数据超时
catch (SocketTimeoutException e) {
break;
}

// 超过数据包末尾
catch (IOException e) {
break;
}
}
} catch (Exception e) {
// 处理socket错误
}

// 休眠1秒后重连
sleep(1000);
} catch (Exception e) {
// 处理sleep错误
}
}

5. 怎么用java的socket进行文件传输谁能给个简单的例子,包括发送端和接收端。

java中的网络信息传输方式是基于TCP协议或者UD协议P的,socket是基于TCP协议的

例子1
(1)客户端程序:
import java.io.*;
import java.net.*;
public class Client
{ public static void main(String args[])
{ String s=null;
Socket mysocket;
DataInputStream in=null;
DataOutputStream out=null;
try{
mysocket=new Socket("localhost",4331);
in=new DataInputStream(mysocket.getInputStream());
out=new DataOutputStream(mysocket.getOutputStream());
out.writeUTF("你好!");//通过 out向"线路"写入信息。
while(true)
{
s=in.readUTF();//通过使用in读取服务器放入"线路"里的信息。堵塞状态,
//除非读取到信息。
out.writeUTF(":"+Math.random());
System.out.println("客户收到:"+s);
Thread.sleep(500);
}
}
catch(IOException e)
{ System.out.println("无法连接");
}
catch(InterruptedException e){}
}
}
(2)服务器端程序:
import java.io.*;import java.net.*;
public class Server
{ public static void main(String args[])
{ ServerSocket server=null;
Socket you=null;String s=null;
DataOutputStream out=null;DataInputStream in=null;
try{ server=new ServerSocket(4331);}
catch(IOException e1){System.out.println("ERRO:"+e1);}
try{ you=server.accept();
in=new DataInputStream(you.getInputStream());
out=new DataOutputStream(you.getOutputStream());
while(true)
{
s=in.readUTF();// 通过使用in读取客户放入"线路"里的信息。堵塞状态,
//除非读取到信息。

out.writeUTF("你好:我是服务器");//通过 out向"线路"写入信息.
out.writeUTF("你说的数是:"+s);
System.out.println("服务器收到:"+s);
Thread.sleep(500);
}
}
catch(IOException e)
{ System.out.println(""+e);
}
catch(InterruptedException e){}
}
}

例子(2)
(1) 客户端
import java.net.*;import java.io.*;
import java.awt.*;import java.awt.event.*;
import java.applet.*;
public class Computer_client extends Applet implements Runnable,ActionListener
{ Button 计算;TextField 输入三边长度文本框,计算结果文本框;
Socket socket=null;
DataInputStream in=null; DataOutputStream out=null;
Thread thread;
public void init()
{ setLayout(new GridLayout(2,2));
Panel p1=new Panel(),p2=new Panel();
计算=new Button(" 计算");
输入三边长度文本框=new TextField(12);计算结果文本框=new TextField(12);
p1.add(new Label("输入三角形三边的长度,用逗号或空格分隔:"));
p1.add( 输入三边长度文本框);
p2.add(new Label("计算结果:"));p2.add(计算结果文本框);p2.add(计算);
计算.addActionListener(this);
add(p1);add(p2);
}
public void start()
{ try
{ //和小程序所驻留的服务器建立套接字连接:
socket = new Socket(this.getCodeBase().getHost(), 4331);
in =new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
}
catch (IOException e){}
if(thread == null)
{ thread = new Thread(this);
thread.start();
}
}
public void run()
{ String s=null;
while(true)
{ try{ s=in.readUTF();//堵塞状态,除非读取到信息。

计算结果文本框.setText(s);
}
catch(IOException e)
{ 计算结果文本框.setText("与服务器已断开");
break;
}
}
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==计算)
{ String s=输入三边长度文本框.getText();
if(s!=null)
{ try { out.writeUTF(s);
}
catch(IOException e1){}
}
}
}
}

(2) 服务器端
import java.io.*;import java.net.*;
import java.util.*;import java.sql.*;
public class Computer_server
{ public static void main(String args[])
{ ServerSocket server=null;Server_thread thread;
Socket you=null;
while(true)
{ try{ server=new ServerSocket(4331);
}
catch(IOException e1)
{ System.out.println("正在监听"); //ServerSocket对象不能重复创建。
}
try{ you=server.accept();
System.out.println("客户的地址:"+you.getInetAddress());
}
catch (IOException e)
{ System.out.println("正在等待客户");
}
if(you!=null)
{ new Server_thread(you).start(); //为每个客户启动一个专门的线程。
}
else
{ continue;
}
}
}
}
class Server_thread extends Thread
{ Socket socket;Connection Con=null;Statement Stmt=null;
DataOutputStream out=null;DataInputStream in=null;int n=0;
String s=null;
Server_thread(Socket t)
{ socket=t;
try { in=new DataInputStream(socket.getInputStream());
out=new DataOutputStream(socket.getOutputStream());
}
catch (IOException e)
{}
}
public void run()
{ while(true)
{ double a[]=new double[3] ;int i=0;
try{ s=in.readUTF();堵塞状态,除非读取到信息。

StringTokenizer fenxi=new StringTokenizer(s," ,");
while(fenxi.hasMoreTokens())
{ String temp=fenxi.nextToken();
try{ a[i]=Double.valueOf(temp).doubleValue();i++;
}
catch(NumberFormatException e)
{ out.writeUTF("请输入数字字符");
}
}
double p=(a[0]+a[1]+a[2])/2.0;
out.writeUTF(" "+Math.sqrt(p*(p-a[0])*(p-a[1])*(p-a[2])));
sleep(2);
}
catch(InterruptedException e){}
catch (IOException e)
{ System.out.println("客户离开");
break;
}
}
}
}

这些例子都是Java2实用教程上的.

6. java中的socket客户端的端口如何绑定

java中的socket客户端只需用服务器所在机器的ip以及服务器的端口作为参数创建一个Socket对象就可以了,客户端的代码可以看下实例:
Socket socket = new Socket("168.160.12.42",9998);
或:
Socket socket = new Socket(InetAddress.getLocalHost(),5678); // 向主机名为InetAddress.getLocalHost()的服务器申请连接

客户机必须知道有关服务器的IP地址,对于着一点Java也提供了一个相关的类InetAddress 该对象的实例必须通过它的静态方法来提供,它的静态方法主要提供了得到本机IP 和通过名字或IP直接得到InetAddress的方法。

in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(),true);

以上的程序代码建立了一个Socket对象,这个对象连接到ip地址为168.160.12.42的主机上、端口为9998的服务器对象。并且建立了输入流和输出流,分别对应服务器的输出和客户端的写入。

阅读全文

与socketjava源代码相关的资料

热点内容
八卦汇总421页pdf 浏览:288
android应用自动升级 浏览:749
远程屏幕监控源码 浏览:569
云服务器的ip怎么查询 浏览:157
大学c语言搜题app在哪里下载 浏览:109
pdf文档被保护 浏览:347
有没有电脑公司网站源码下载 浏览:231
智能电视哪个app看电影好用 浏览:226
微信页面源码下载 浏览:959
怎么看5代喷头加密 浏览:361
linux查找文件并删除文件 浏览:872
单片机里的编程软件 浏览:166
钻石投票网站源码 浏览:975
cidrphp 浏览:882
android测试用例文档 浏览:822
单片机素数 浏览:840
怎么在桌面上发送文件夹 浏览:761
海外贷款源码 浏览:719
北航单片机实验 浏览:801
私有云服务器在哪里 浏览:941