程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> 簡單的例子 c與java socket通信

簡單的例子 c與java socket通信

編輯:關於JAVA
 

c 服務器

#include "unp.h"
#include <time.h>
#include "stdio.h"
int main(int argc, char **argv)
{
int listenfd, connfd;
struct sockaddr_in servaddr;
char buff[MAXLINE];
char output[MAXLINE];
time_t ticks;

printf("綁定前\n");

listenfd = socket(AF_INET, SOCK_STREAM, 0);

printf("綁定前\n");
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(8888); /* daytime server*/


printf("綁定前");
bind(listenfd, (SA *) &servaddr, sizeof(servaddr));
printf("綁定結束%d",listenfd);
listen(listenfd,5);
printf("kaishi監聽\n");

 

connfd = accept(listenfd, (SA *) NULL, NULL);

ticks = time(NULL);
snprintf(buff, sizeof(buff), "%.24sguohaitao\r\n", ctime(&ticks));
printf("time=%.24s Hello! Enter BYE to exit.\n ",buff);
// write(connfd, buff, strlen(buff));
// int done = 0;
//bzero(buff,MAXLINE);
int n;
for(;;){
n=read(connfd,output,MAXLINE);
output[n]=0;
printf("%s",output);
if(n<=0)
break;
// done = ;
//else{
// write(connfd,output,strlen(output));
// }
//if(fputs(buff,stdout)==EOF)
//{
// printf("標准輸入錯誤!");
}
// }
close(connfd);
// return 0;
}

 

 

 

java 客戶

import java.io.*;
import java.net.*;
import java.util.Scanner;
public class ClientDemo {

/**
* @param args
*/
public static void main(String[] args) {
Socket socket = null;
try {
socket = new Socket("127.0.0.1",8888);

//獲取輸出流,用於客戶端向服務器端發送數據

// DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
//獲取輸入流,用於接收服務器端發送來的數據
// DataInputStream dis = new DataInputStream(socket.getInputStream());
//客戶端向服務器端發送數據

// dos.writeUTF("ssssssssssss!");
//打印出從服務器端接收到的數據
// System.out.println(dis.readUTF());
//不需要繼續使用此連接時,記得關閉哦
/*
InputStream ips = socket.getInputStream();
InputStreamReader ipsr = new InputStreamReader(ips);
BufferedReader br = new BufferedReader(ipsr);
String s = "";
// while((s = br.readLine()) != null)
System.out.println(s);
*/

/*
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(),true);
String info;
info=input.readLine();
*/
OutputStream ido = socket.getOutputStream();
PrintWriter pw = new PrintWriter(ido,true);
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String sInput;

while(true){
sInput = in.readLine();
// out.println(sInput);
if(sInput.equalsIgnoreCase("bye"))
break;
// info=input.readLine();
pw.println(sInput);
// ips.close();
// ido.close();
}
socket.close();





} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}


 

###留著以後做的更復雜1!!!
 

 
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved