JAVA CLIENT
//java client
package hello.FileUpload;
import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
public class JavaSocketClient{
public static void main(String[] args) throws IOException {
JavaSocketClient cm = new JavaSocketClient();
cm.run();
}
void run() throws IOException {
//소켓 생성
Socket socket = new Socket();
//서버쪽 주소 생성. ip는 localhost, 포트는 9999. 필요에 맞게 바꾸기
SocketAddress address = new InetSocketAddress("127.0.0.1", 9999);
//주소에 해당하는 서버랑 연결
socket.connect(address);
System.out.println("CONNECT OK");
try {
//받기
receive_my(socket);
System.out.println("recieve ok");
//보내기
send_Image(socket);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void send_Image(Socket socket) throws IOException {
try{
DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());
File fp = new File("/home/dahyeon/123.png");
FileInputStream fs = new FileInputStream(fp);
if(fs == null)
return;
BufferedInputStream br_file = new BufferedInputStream(fs);
int temp = 0;
byte[] data = new byte[256];
while((temp=br_file.read(data))!=-1){
DOS.write(data, 0, temp);
}
DOS.flush();
DOS.close();
br_file.close();
fs.close();
}catch (Exception ex){
System.out.println(ex);
}finally{
try{
if(socket!=null) socket.close();
}catch (Exception ex){}
}
}
public static void send(Socket socket) throws IOException {
//Person 객체 생성. 인자로 3 넣어줌.
Person person = new Person(3);
//생성한 person 객체를 byte array로 변환
byte[] data = toByteArray(person);
//서버로 내보내기 위한 출력 스트림 뚫음
OutputStream os = socket.getOutputStream();
//출력 스트림에 데이터 씀
os.write(data);
//보냄
os.flush();
}
public static void receive_my(Socket socket) throws IOException {
//수신 버퍼의 최대 사이즈 지정
int maxBufferSize = 20;
//버퍼 생성
byte[] recvBuffer = new byte[maxBufferSize];
//서버로부터 받기 위한 입력 스트림 뚫음
InputStream is = socket.getInputStream();
//버퍼(recvBuffer) 인자로 넣어서 받음. 반환 값은 받아온 size
int nReadSize = is.read(recvBuffer);
//System.out.println(recvBuffer);
//받아온 값이 0보다 클때
if (nReadSize > 0) {
//받아온 byte를 Object로 변환
//Person receivePerson = toObject(recvBuffer, Person.class);
String data = new String(recvBuffer);
//확인을 위해 출력
System.out.println(data);
}
}
public static void receive(Socket socket) throws IOException {
//수신 버퍼의 최대 사이즈 지정
int maxBufferSize = 256;
//버퍼 생성
byte[] recvBuffer = new byte[maxBufferSize];
//서버로부터 받기 위한 입력 스트림 뚫음
InputStream is = socket.getInputStream();
//버퍼(recvBuffer) 인자로 넣어서 받음. 반환 값은 받아온 size
int nReadSize = is.read(recvBuffer);
//받아온 값이 0보다 클때
if (nReadSize > 0) {
//받아온 byte를 Object로 변환
//Person receivePerson = toObject(recvBuffer, Person.class);
String data = new String(recvBuffer);
//확인을 위해 출력
System.out.println(data);
}
}
public static byte[] toByteArray (Object obj)
{
byte[] bytes = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
oos.close();
bos.close();
bytes = bos.toByteArray();
}
catch (IOException ex) {
//TODO: Handle the exception
}
return bytes;
}
public static <T> T toObject (byte[] bytes, Class<T> type)
{
Object obj = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream (bytes);
ObjectInputStream ois = new ObjectInputStream (bis);
obj = ois.readObject();
}
catch (IOException ex) {
//TODO: Handle the exception
}
catch (ClassNotFoundException ex) {
//TODO: Handle the exception
}
return type.cast(obj);
}
}
class Person implements Serializable {
int age;
Person(int age) {
this.age= age;
}
}
이거는 여러 코드를 짜집기해서 헷갈릴 수 있지만 중요한 부분은 아래 부분이다.
아래에서 쓰인 함수들만 사용하였고 send_Image(socket); 함수가 이미지를 보낼 때 쓰는 함수이다.
void run() throws IOException {
//소켓 생성
Socket socket = new Socket();
//서버쪽 주소 생성. ip는 localhost, 포트는 9999. 필요에 맞게 바꾸기
SocketAddress address = new InetSocketAddress("127.0.0.1", 9999);
//주소에 해당하는 서버랑 연결
socket.connect(address);
System.out.println("CONNECT OK");
try {
//받기
receive_my(socket);
System.out.println("recieve ok");
//이미지 전송
send_Image(socket);
} catch (IOException e) {
e.printStackTrace();
}
}
C SERVER
/* server.c */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
void error_handling(char *message);
int main(int argc, char *argv[])
{
int serv_sock;
int clnt_sock;
char buf[256];
struct sockaddr_in serv_addr;
struct sockaddr_in clnt_addr;
socklen_t clnt_addr_size;
char message[]="Hello World!";
if(argc!=2){
printf("Usage : %s <port>\n", argv[0]);
exit(1);
}
serv_sock=socket(PF_INET, SOCK_STREAM, 0);
if(serv_sock == -1)
error_handling("socket() error");
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);
serv_addr.sin_port=htons(atoi(argv[1]));
if(bind(serv_sock, (struct sockaddr*) &serv_addr, sizeof(serv_addr))==-1 )
error_handling("bind() error");
if(listen(serv_sock, 5)==-1)
error_handling("listen() error");
clnt_addr_size=sizeof(clnt_addr);
clnt_sock=accept(serv_sock, (struct sockaddr*)&clnt_addr,&clnt_addr_size);
if(clnt_sock==-1)
error_handling("accept() error");
write(clnt_sock, message, sizeof(message));
printf("test message send\n");
int nbyte = 256;
size_t filesize = 0, bufsize = 0;
FILE *file = NULL;
file = fopen("aurora.png"/* 새로 만들 파일 이름 */, "wb");
bufsize = 256;
while(/*filesize != 0*/nbyte!=0) {
nbyte = recv(clnt_sock, buf, bufsize, 0);
fwrite(buf, sizeof(char), nbyte, file);
//nbyte = 0;
}
fclose(file);
close(clnt_sock);
close(serv_sock);
return 0;
}
void error_handling(char *message)
{
fputs(message, stderr);
fputc('\n', stderr);
exit(1);
}
우선 Hello World! 라는 문자를 보낸 후 파일을 수신 받는다.
파일을 수신 받은 후에는 aurora.png 파일에 저장한다.
작동
- 서버 실행
9999 포트로 서버를 실행시켰다.
java 코드를 실행시키면
더보기
java와 C가 통신하려면 Byte를 이용해야 한다.
'프로젝트 > 21후반기 광운대 바람 작품' 카테고리의 다른 글
[2021 후반기 작품 완성] 분산 처리 서버 (0) | 2021.11.23 |
---|---|
[HAProxy] TCP 로드밸런싱 (0) | 2021.11.17 |
[AWS EC2] EC2 인스턴트 생성 및 GUI 설치 (0) | 2021.11.02 |
[SpringBoot] 파일 업로드 서버 구축 - 10/6, 11/3 (0) | 2021.10.06 |
제안서-분산 처리 서버 구축 (0) | 2021.09.18 |